PHP PDO Неопределенная ошибка индекса при использовании класса Fileuploader - PullRequest
0 голосов
/ 16 октября 2018

Привет, я работаю над проектом, в котором я хочу использовать этот класс file-uploader, но постоянно получаю эту ошибку:

**Notice:** Undefined index: filename in C:\xampp\htdocs\proceskontrol\partials\newtype.php on line 8

Есть идеи, как ее можно исправить?

Я на 99,9% уверен, что это что-то с моей формой, но я не вижу этого.класс не мой получил его от учителя в моей школе.

newtype.php Это моя страница формы:

<?php
    $fileUploader = new FileUploader("../assets/img/type_img/");

    if (isset($_POST["btn_type_send"]) && !empty($_POST["btn_type_send"])) {
        $newfile = $fileUploader->fileUpload($_FILES['filUpload'], 250, 250);
        $error = [];
        $prodId = $products->newType($_POST, $newfile['filename']);
            if ($newfile['success'] == true){
                $notification->setNewProductNotificationSuccess();
                $success = '<div class="alert success" data-dismiss="alert" id="myAlert">
                                <a href="#" class="close">&times;</a>
                                <i class="glyphicon glyphicon-warning-sign"></i>
                                Product '.$_POST['name'].' is created!
                                </div>';
            } else {
                echo $newfile['msg'];
        }
    }
    ?>

    <div class="page-body">
        <?=@$success?>
        <div class="col-md-8 offset-2">
            <form name="filUpload" action="#" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="name">Navn</label>
                        <?=@$error['name']?>
                    <input type="text" name="name" id="name" class="form-control" value="<?= @$_POST['name'] ?>">
                </div>
                <!-- Image upload card start -->
                <div class="card">
                    <div class="card-header">
                      <h5>Billede Upload</h5>
                    </div>
                    <div class="card-block">
                        <div class="sub-title">Vælg et billede</div>
                        <input type="file" name="filUpload" id="filer_input" multiple="multiple">
                    </div>
                </div>
                <!-- Image upload card end -->

                <div class="input-group">
                    <input type="submit" style="margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Submit" name="btn_type_send" />
                </div>
            </form>
        </div>
    </div>

FileUploader.phpИ это мой класс:

<code><?php

class FileUploader{
    private $_errors = [
        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
        3 => "The uploaded file was only partially uploaded",
        4 => "No file was uploaded",
        6 => "Missing a temporary folder. Introduced in PHP 5.0.3",
        7 => "Failed to write file to disk. Introduced in PHP 5.1.0",
        8 => "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0."
    ];
    private $_fileFolder;
    private $_thumbFolder;
    public $mimetype = [
        'image/png',
        'image/jpeg',
        'image/jpg',
        'image/gif'
    ];
    protected $currentFile = NULL;

// try to avoid using 0777
    public function __construct($fileFolder, $thumbFolder = null)
    {
        $this->_fileFolder = $fileFolder;
        if(!file_exists($this->_fileFolder)){
            mkdir($this->_fileFolder, 0777, true);
        }

        if($thumbFolder === null){
            $this->_thumbFolder = $fileFolder . 'thumb/';
        }

        if(!file_exists($this->_thumbFolder)){
            mkdir($this->_thumbFolder, 0777, true);
        }
    }

    /**
     * Undocumented function
     *
     * @param string $fileInput
     * @return array
     */
    public function fileUpload($fileInput, $maxWidth = null, $maxHeight = null, $quality = null)
    {
        if(isset($fileInput)) {
//            echo "<pre>",print_r($_FILES),"
"; $ this-> currentFile = $ fileInput; // проверка наличия ошибок кода, соответствующих нашим сообщениям об ошибках, если (array_key_exists ($ this-> currentFile ['ошибка '] [0], $ this -> _ ошибки)) {return [' success '=> false,' msg '=> $ this -> _ errors [$ this-> currentFile [' error '] [0]]];} // Проверка допустимости mimetype if (! In_array ($ this-> currentFile ['type'] [0], $ this-> mimetype)) {return ['success' => false, 'msg' => «Загруженный тип файла не разрешен!»];} $ NewName = time (). '_'. $ This-> currentFile ['name'] [0]; if (move_uploaded_file ($ this-> currentFile ["tmp_name "] [0], $ this -> _ fileFolder. $ newName)) {if ($ maxWidth! == null && $ maxHeight! == null) {if (($ this-> currentFile ['type'] [0] === 'image / jpg') || ($ this-> currentFile ['type'] [0] === 'image / jpeg')) {if ($ quality! == null) {imagejpeg ($this-> resizeImage ($это -> _ fileFolder.$ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder.$ newName, $ quality);} else {imagejpeg ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] [0] === 'image / png') {if ($ quality! == null) {imagepng ($ this-> resizeImage ($ this -> _ fileFolder). $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName, $ quality);} else {imagepng ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] [0] === 'image / gif') {imagegif ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} return ['success' => true, 'msg' => "Файл".базовое имя ($ this -> _ fileFolder. $ newName)."был загружен.", 'filename' => $ newName];} else {return ['success' => false, 'msg' => "Извините, при загрузке файла произошла ошибка."];}}} / ** * Недокументированная функция * * @param string $ fileInput * @return array * / открытая функция fileUploadEdit ($ fileInput, $ maxWidth = null, $ maxHeight = null, $ quality = null) {if (isset ($)fileInput)) {// echo "
",print_r($_FILES),"
";$ this-> currentFile = $ fileInput;// проверка наличия ошибок кода, соответствующих нашим сообщениям об ошибках if (array_key_exists ($ this-> currentFile ['error'] [0], $ this -> _ errors)) {return ['success' => false, 'msg'=> $ this -> _ errors [$ this-> currentFile [' error '] [0]]];} // проверка, разрешен ли тип mimeif (! in_array ($ this-> currentFile ['type'] [0], $ this-> mimetype)) {return ['success' => false, 'msg' => "Загруженный тип файла недопустим!"];} $ newName = time ().'_'.$ This-> CurrentFile [ 'имя'] [0];if (move_uploaded_file ($ this-> currentFile ["tmp_name"] [0], $ this -> _ fileFolder. $ newName)) {if ($ maxWidth! == null && $ maxHeight! == null) {if (($this-> currentFile ['type'] [0] === 'image / jpg') || ($ this-> currentFile ['type'] [0] === 'image / jpeg')) {if ($ quality! == null) {imagejpeg ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this->_thumbFolder. $ newName, $ quality);} else {imagejpeg ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] [0] === 'image / png') {if ($ quality! == null) {imagepng ($ this-> resizeImage ($ this -> _ fileFolder). $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName, $ quality);} else {imagepng ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] [0] === 'image / gif') {imagegif ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'] [0], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} return ['success' => true, 'msg' => "Файл".базовое имя ($ this -> _ fileFolder. $ newName)."был загружен.", 'filename' => $ newName];} else {return ['success' => false, 'msg' => "Извините, при загрузке файла произошла ошибка."];}}} публичная функция fileUploadEditUser ($ fileInput, $ maxWidth = null, $ maxHeight = null, $ quality = null) {if (isset ($ fileInput)) {// echo "
",print_r($_FILES),"
";$ this-> currentFile = $ fileInput;// проверка наличия ошибок кода, соответствующих нашим сообщениям об ошибках if (array_key_exists ($ this-> currentFile ['error'], $ this -> _ errors)) {return ['success' => false, 'msg' =>$ this -> _ errors [$ this-> currentFile ['error']]];} // проверка допустимости mimetype, если (! in_array ($ this-> currentFile ['type'], $ this-> mimetype)) {return ['success' => false, 'msg' => "Загруженный файлТип файла не допускается!];} $ newName = time ().'_'.$ This-> CurrentFile [ 'имя'];if (move_uploaded_file ($ this-> currentFile ["tmp_name"], $ this -> _ fileFolder. $ newName)) {if ($ maxWidth! == null && $ maxHeight! == null) {if (($ this->currentFile ['type'] === 'image / jpg') || ($ this-> currentFile ['type'] === 'image / jpeg')) {if ($ quality! == null) {imagejpeg($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName, $ quality);} еще {imagejpeg ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] === 'image / png') {if ($ quality! == null) {imagepng ($ this-> resizeImage ($ this -> _ fileFolder. $ newName), $ this-> currentFile ['type'], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName, $ quality);} else {imagepng ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type'], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} if ($ this-> currentFile ['type'] === 'image / gif') {imagegif ($ this-> resizeImage ($ this -> _ fileFolder. $ newName, $ this-> currentFile ['type')], $ maxWidth, $ maxHeight), $ this -> _ thumbFolder. $ newName);}} return ['success' => true, 'msg' => "Файл".базовое имя ($ this -> _ fileFolder. $ newName)."был загружен.", 'filename' => $ newName];} else {return ['success' => false, 'msg' => "Извините, при загрузке файла произошла ошибка."];}}} / ** * @param $ filename * @param $ mime * @param $ max_width * @param $ max_height * @return resource * / приватная функция resizeImage ($ filename, $ mime, $ max_width, $ max_height) {список($ orig_width, $ orig_height) = getimagesize ($ filename);$ width = $ orig_width;$ height = $ orig_height;# выше if ($ height> $ max_height) {$ width = ($ max_height / $ height) * $ width;$ height = $ max_height;} # шире if ($ width> $ max_width) {$ height = ($ max_width / $ width) * $ height;$ width = $ max_width;} $ image_p = imagecreatetruecolor ($ width, $ height);imagealphablending ($ image_p, false);imagesavealpha ($ image_p, true);$ transparent = imagecolorallocatealpha ($ image_p, 255, 255, 255, 127);imagefilledrectangle ($ image_p, 0, 0, $ ширина, $ высота, $ прозрачный);if (($ mime === 'image / jpeg') || ($ mime === 'image / jpg')) {$ image = imagecreatefromjpeg ($ filename);} if ($ mime === 'image / png') {$ image = imagecreatefrompng ($ filename);} if ($ mime === 'image / gif') {$ image = imagecreatefromgif ($ filename);} imagecopyresampled ($ image_p, $ image, 0, 0, 0, 0, $ width, $ height, $ orig_width, $ orig_height);вернуть $ image_p;}}

1 Ответ

0 голосов
/ 16 октября 2018

Глядя на ваш код, особенно на эту часть:

        }
        return [
            'success' => true,
            'msg' => "The file ". basename($this->_fileFolder . $newName). " has been uploaded.",
            'filename' => $newName
        ];
    } else {
        return [
            'success' => false,
            'msg' => "Sorry, there was an error uploading your file."
        ];
    }

При неудачной загрузке файла вы не возвращаете индекс filename, поэтому, возможно, ваша загрузка не удалась и вы не проверяли ееперед доступом к filename.

Перед доступом к filename следует проверить наличие ошибок или вернуть пустой индекс filename, т. е.

$newfile = $fileUploader->fileUpload($_FILES['filUpload'], 250, 250);
$error = [];
    if ($newfile['success'] == true){
        $prodId = $products->newType($_POST, $newfile['filename']);
        // ...
    } else {
        echo $newfile['msg'];
    }
...