user10511312
user10511312

Reputation:

PHP PDO Undefined index error Using Fileuploader class

Hi I'm working on a project where I want to use this file-uploader class, but i keep getting this error :

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

Any idea how it can be fixed?

I am 99,9% sure its something with my form but I can't see it. the class is not mine got it from a teacher at my school.

newtype.php This is my form page:

<?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 And this is my class:

<?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),"</pre>";

            $this->currentFile = $fileInput;
            // checking if there is code errors that match our error messages
            if(array_key_exists($this->currentFile['error'][0], $this->_errors)){
                return [
                    'success' => false,
                    'msg' => $this->_errors[$this->currentFile['error'][0]]
                ];
            }
            // Checking if the mimetype is allowed
            if(!in_array($this->currentFile['type'][0], $this->mimetype)){
                return [
                    'success' => false,
                    'msg' => "The uploaded file type is not allowed!"
                ];
            }
            $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($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' => "The file ". basename($this->_fileFolder . $newName). " has been uploaded.",
                    'filename' => $newName
                ];
            } else {
                return [
                    'success' => false,
                    'msg' => "Sorry, there was an error uploading your file."
                ];
            }
        }
    }

    /**
     * Undocumented function
     *
     * @param string $fileInput
     * @return array
     */
    public function fileUploadEdit($fileInput, $maxWidth = null, $maxHeight = null, $quality = null)
    {
        if(isset($fileInput)) {
//            echo "<pre>",print_r($_FILES),"</pre>";

            $this->currentFile = $fileInput;
              // checking if there is code errors that match our error messages
            if(array_key_exists($this->currentFile['error'][0], $this->_errors)){
                return [
                    'success' => false,
                    'msg' => $this->_errors[$this->currentFile['error'][0]]
                ];
            }
            // checking if the mime type is allowed
            if(!in_array($this->currentFile['type'][0], $this->mimetype)){
                return [
                    'success' => false,
                    'msg' => "The uploaded file type is not allowed!"
                ];
            }
            $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($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' => "The file ". basename($this->_fileFolder . $newName). " has been uploaded.",
                    'filename' => $newName
                ];
            } else {
                return [
                    'success' => false,
                    'msg' => "Sorry, there was an error uploading your file."
                ];
            }
        }
    }

    public function fileUploadEditUser($fileInput, $maxWidth = null, $maxHeight = null, $quality = null)
    {
        if(isset($fileInput)) {
//            echo "<pre>",print_r($_FILES),"</pre>";

            $this->currentFile = $fileInput;
            // checking if there is code errors that match our error messages
            if(array_key_exists($this->currentFile['error'], $this->_errors)){
                return [
                    'success' => false,
                    'msg' => $this->_errors[$this->currentFile['error']]
                ];
            }
            // checking if the mimetype is allowed
            if(!in_array($this->currentFile['type'], $this->mimetype)){
                return [
                    'success' => false,
                    'msg' => "The uploaded file type is not allowed!"
                ];
            }
            $newName = time() . '_' . $this->currentFile['name'];
            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);
                        } else {
                            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' => "The file ". basename($this->_fileFolder . $newName). " has been uploaded.",
                    'filename' => $newName
                ];
            } else {
                return [
                    'success' => false,
                    'msg' => "Sorry, there was an error uploading your file."
                ];
            }
        }
    }


    /**
     * @param $filename
     * @param $mime
     * @param $max_width
     * @param $max_height
     * @return resource
     */
    private function resizeImage($filename, $mime, $max_width, $max_height)
    {
        list($orig_width, $orig_height) = getimagesize($filename);
        $width = $orig_width;
        $height = $orig_height;
        # taller
        if ($height > $max_height) {
            $width = ($max_height / $height) * $width;
            $height = $max_height;
        }
        # wider
        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, $width, $height, $transparent);
        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);
        return $image_p;
    }
}

Upvotes: 1

Views: 213

Answers (1)

Gonzalo
Gonzalo

Reputation: 1876

Looking at your code, specially this part:

        }
        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."
        ];
    }

When your file upload fails you doesn't return any filename index, so, probably your upload is failing and you are not checking it before accessing filename.

You should check for errors before access filename, or return an empty filename index, ie:

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

Upvotes: 1

Related Questions