1

Приветствую всех, кто наткнется на мой пост. В общем, есть HTML форма для создания новой темы на форуме, пользователь может добавить название, описание и если желает фото. Я же хочу достичь того, чтоб даже если, пользователь не выбрал изображения можно было добавить все остальное без загрузки изображений. На данный момент после того как нажат Submit и даже если изображения не выбраны пустые файлы все равно загружаются в ДБ. Вот мой код:

<div class="main col-md-9 col-md-offset-3">
  <center><h2>Start New Topic</h2></center>
  <form accept-charset="UTF-8" action="" method="POST" enctype="multipart/form-data">

  <div class="form-group">
  <label>Title*</label>
    <input type='text' class="form-control" id="title" name='title' value='' maxlength="155" required>
  <h6 class="pull-right" id="count_title"></h6>
  </div>

  <div class="form-group">
    <label for="sel1">Category</label>
    <select class="form-control" id="sel1">
      <option>none</option>
      <option>Movies</option>
      <option>Politics</option>
      <option>Celebreties</option>
      <option>Music</option>
      <option>Books</option>
      <option>Various</option>
    </select>
  </div>
  <div class="form-group">
    <label>Include Description</label>
    <textarea class="form-control" id="description" name='description' cols='60' rows='10' maxlength="5550"></textarea>
  <h6 class="pull-right" id="count_description"></h6>
  </div>
  <div class="form-group">
  <label>Include Images</label>
  <input type="file" name="files[]" multiple="" />
  </div>

  <div class="form-group pull-right">
  <input type='submit' class="btn btn-info btn-md" name='submit' value='Go!'>
  </div>
    </form>

PHP script:

//if form has been submitted process it
if(isset($_POST['submit'])){
    $_POST = array_map( 'stripslashes', $_POST );

    //collect form data
    extract($_POST);
//basic validation
if($title ==''){
  $error[] = 'Please enter the title.';
}
    if(!isset($error)){

        try {
    $title = htmlspecialchars($title);
    $description = htmlspecialchars($description);
    //insert into database
    $stmt = $db->prepare('INSERT INTO topics (title,description,date_started) VALUES (:title, :seotitle, :description, NOW())');
    $stmt->execute(array(
      ':title' => $title,
      ':seotitle' => $seotitle,
      ':description' => $description
    ));
    $last_id = $db->lastInsertId();

    //inserting images
    if(isset($_FILES['files'])){
        $errors= array();
      foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = 'loorha_'.$user_id.'_'.$last_id.'_'.$key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
            if($file_size > 2000000){
          $errors[]='File size must be less than 2 MB';
            }
            //Storing Images into DB
            $stmt = $db->prepare('INSERT INTO topics_images (topic_id,user_id,img_name,size,type,time_uploaded) VALUES ("'.$last_id.'","'.$user_id.'","'.$file_name.'", "'.$file_size.'", "'.$file_type.'",NOW())');
            $stmt->execute();

            $destinationFolder ="uploads/topic/$last_id";
            if(empty($errors)==true){
                if(is_dir($destinationFolder)==false){
                    mkdir("$destinationFolder", 0700);      // Create directory if it does not appear in the root folder
                }
                if(is_dir("$destinationFolder/".$file_name)==false){
            $file_name = $destinationFolder. "/".$file_name;
                    move_uploaded_file($file_tmp, $file_name);


                }else{  //rename the file if another one exist
                    $new_dir="$destinationFolder/".$file_name.time();
                     rename($file_tmp,$new_dir) ;
                }

            }else{
                    print_r($errors);
            }
        }
      if(empty($error)){
        echo "Images Uploaded Successfully!";
      }
    }
    //redirect to just created topic
    header('Location: topic/' . $last_id . '/' . $seotitle);
    exit;

        } catch(PDOException $e) {
            echo $e->getMessage();
        }

    }

}

Я попытался сделать это с помощью if(isset($_FILES['files'])){ но все равно, не работает правильно. Буду рад любому совету или помощи! Спасибо!

1 ответ 1

0

Здравствуйте.

Ознакомтесь тут

If no file is selected for upload in your form, PHP will return $_FILES['files']['size'] as 0, and $_FILES['files']['tmp_name'] as none.

5
  • Hm, now i'm gonna spend whole night wondering how to fix it up... 10 июн 2017 в 18:41
  • Спасибо за ответ и наводку) 10 июн 2017 в 18:42
  • Пожалуйста. ;-)
    – Vladimir
    10 июн 2017 в 18:48
  • Исправить надо в проверке условия. Вместо if(isset($_FILES['files'])) укажите if($_FILES['files']['size'] != 0) или if(isset($_FILES['files']['tmp_name']))
    – Vladimir
    10 июн 2017 в 18:50
  • Спасибо, я уже примерно понял что и как, сделаю) 10 июн 2017 в 18:55

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.