Почему моя функция загрузки файлов не работает должным образом? PHP - PullRequest
0 голосов
/ 07 января 2020

Привет, у меня есть функция загрузки файлов. Управляет размером файла и типом файла . Если файл в формате PDF и его размер меньше 10 МБ, все работает должным образом.

Если файл не PDF, он должен показать мне сообщение: «ОШИБКА: Вы можете просто загрузить файлы PDF». но без сообщения.

Если размер файла превышает 10 МБ, он должен показать мне сообщение: «ОШИБКА: Максимальный размер файла 10 МБ». но без сообщения.

Если файл PDF, но его размер превышает 10 МБ, он показывает мне: «ОШИБКА: все поля должны быть заполнены».

Что не так с мой код?

Функция:

<?php

function file_create($file) {

    if(isset($file)){

        $errors     = array();
        $target_dir = "../files/";
        $file_name  = uniqid();
        $file_size  = $file['size'];
        $file_tmp   = $file['tmp_name'];
        $file_type  = $file['type'];
        $file_ext   = strtolower(end(explode('.',$file['name'])));

        if($file_type != "application/pdf") {

            $error = "ERROR : You can upload just PDF files.";
            array_push($errors, $error);

        }

        if($file_size > 1024*1024*10) {

            $error = "ERROR : Max file size 10MB.";
            array_push($errors, $error);

        }

        if(empty($errors) == true) {

            move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);

            $errors['status'] = true;
            $errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);

        } else {

            $errors['status'] = false;

        }

        return $errors;

    }

}

?>

Другой файл:

<?php

$errors = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $notice_title       = secured_post("notice-title");
    $notice_content     = secured_post("notice-content");

    // if there is empty field in form.
    if (multi_empty($notice_title, $notice_content)) {

        // if a file submitted.
        if (isset($_FILES['notice-file'])) {

            $notice_file = $_FILES['notice-file'];

            // upload the file.
            $upload = file_create($notice_file);

            if ($upload['status'] == false) {

                $size = count($upload);

                for ($i=0; $i < $size; $i++) { 

                    array_push($errors, $upload[$i]);

                }

            }

            notice_create($conn, $notice_title, $notice_content, $upload['patch']);

        } else {

            notice_create($conn, $notice_title, $notice_content);

        }

    } else {

        $error = "ERROR : All fields must be filled.";
        array_push($errors, $error);

    }

}

if ($errors) {

    foreach ($errors as $error) {

        echo "<div class='error'>".$error."</div></br>";

    }

}

?>

1 Ответ

0 голосов
/ 08 января 2020

Вот проблема. Если размер вашего файла превышает 10 МБ, загрузка файла может занять некоторое время, поэтому вам необходимо проверить, пуст ли массив $_FILES или нет.

Попробуйте выполнить следующее:

<?php
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_FILES)) {  //I've made changes to this line
    $notice_title       = secured_post("notice-title");
    $notice_content     = secured_post("notice-content");
    // if there is empty field in form.
    if (multi_empty($notice_title, $notice_content)) {
        // if a file submitted.
        if (isset($_FILES['notice-file'])) {
            $notice_file = $_FILES['notice-file'];
            // upload the file.
            $upload = file_create($notice_file);
            if ($upload['status'] == false) {
                $size = count($upload);
                for ($i=0; $i < $size; $i++) { 
                    array_push($errors, $upload[$i]);
                }
            }
            notice_create($conn, $notice_title, $notice_content, $upload['patch']);
        } else {
            notice_create($conn, $notice_title, $notice_content);
        }
    } else {
        $error = "ERROR : All fields must be filled.";
        array_push($errors, $error);
    }
}
if ($errors) {
    foreach ($errors as $error) {
        echo "<div class='error'>".$error."</div></br>";
    }
}
?>

И:

<?php
function file_create($file) {
    if(!empty($file)){  //I've made changes to this line
        $errors     = array();
        $target_dir = "../files/";
        $file_name  = uniqid();
        $file_size  = $file['size'];
        $file_tmp   = $file['tmp_name'];
        $file_type  = $file['type'];
        $file_ext   = strtolower(end(explode('.',$file['name'])));
        if($file_type != "application/pdf" || $file_ext != ".pdf") {  //I've made changes to this line
            $error = "ERROR : You can upload just PDF files.";
            array_push($errors, $error);
        }
        if($file_size > (1024*1024*10)) {
            $error = "ERROR : Max file size 10MB.";
            array_push($errors, $error);
        }
        if(empty($errors) == true) {
            move_uploaded_file($file_tmp,$target_dir.$file_name.".".$file_ext);
            $errors['status'] = true;
            $errors['patch'] = substr($target_dir.$file_name.".".$file_ext, 3);
        } else {
            $errors['status'] = false;
        }
        return $errors;
    }
}
?>

Примечание: Массив $_FILES может быть установлен и пуст в одно и то же время, поэтому isset() здесь вам не поможет.

...