1

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;
    }
}
PersianMan
  • 924
  • 1
  • 12
  • 29
  • 1
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – AnTrakS Oct 16 '18 at 07:50
  • Have you tried var_dump on $newfile? To see what the structure of the variable looks like? – Royal Wares Oct 16 '18 at 07:52
  • it said this Notice: Undefined variable: newfile in C:\xampp\htdocs\proceskontrol\partials\newtype.php on line 20 NULL –  Oct 16 '18 at 07:57
  • does it mean i doesnt get the $newfile sry im pretty new at coding php :P –  Oct 16 '18 at 07:58
  • 1-in your browser press F12 and go to Network tab, then submit form and see http params ... 2- in php var_dump ```$_FILES``` variable – PersianMan Oct 16 '18 at 08:00
  • Well that explains it, you're trying to use something that doesn't exist. if $newfile is null that means it hasn't been set at all, as a consequence trying to find "filename" within that variable is impossible. It's like trying to find the bedroom of a house, but you're stood in the middle of the forrest without a house to go into in the first place. – Royal Wares Oct 16 '18 at 08:00
  • Also, the thing responsible for filling out that variable is on the previous line: $fileUploader->fileUpload($_FILES['filUpload'], 250, 250); I don't think this is doing what you expect it to do so you'll need to dive into that class (if you wrote it) to find out more, or if it's a library you need to read their documentation on how to use the class. – Royal Wares Oct 16 '18 at 08:02
  • Notice: Undefined index: filename in C:\xampp\htdocs\proceskontrol\partials\newtype.php on line 8 The uploaded file type is not allowed!array(1) { ["filUpload"]=> array(5) { ["name"]=> string(17) "064-01-04 (5).JPG" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "C:\xampp\tmp\php15DC.tmp" ["error"]=> int(0) ["size"]=> int(115795) } } –  Oct 16 '18 at 08:03
  • it's a class that ive got from my teacher... so can't reallt get any info about it anymore since its quite some time ago. –  Oct 16 '18 at 08:05
  • it makes sense but i dont know how i could correct it. –  Oct 16 '18 at 08:09
  • Tried using the var_dump on the $newfile, and got this as result Notice: Undefined index: filename in C:\xampp\htdocs\proceskontrol\partials\newtype.php on line 8 The uploaded file type is not allowed!array(2) { ["success"]=> bool(false) ["msg"]=> string(38) "The uploaded file type is not allowed!" } –  Oct 16 '18 at 08:21
  • The clue is there, "The uploaded file type is not allowed!", it looks like the class is doing the right thing, however your code isn't checking for those errors before assuming that everything went okay. – Royal Wares Oct 16 '18 at 08:34
  • Have you read through the FileUploader.php? It's not a very big class so it's reasonable to read it all. It would probably give you a really good understanding of the flow of code and how to work with it. – Royal Wares Oct 16 '18 at 08:36
  • ive read it some times, but must admit never gave it much thought since i was sure my error was from my form. ill read it again, and see if i can fix my problem. Thanks again for your help :) –  Oct 16 '18 at 08:40
  • i actually have a question that is abit off topic about my class. because ive heard that using 0777 is 99% bad practice. is that true? and if so, how could I fix it? –  Oct 16 '18 at 08:45
  • like this if(!file_exists($this->_thumbFolder)){ mkdir($this->_thumbFolder, 0777, true); } –  Oct 16 '18 at 08:46
  • ive read the class and understand most of it now, there is some parts that i know what does but i can't explain correctly how it does it. like the $newName i know it changes the name of the image file that is copied into the database but i can't explain how it get the random name. i know its something using the time() –  Oct 16 '18 at 09:00

1 Answers1

1

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'];
    }
Gonzalo
  • 1,781
  • 15
  • 29
  • I get data into my database "the type name" but the image doesnt follow. –  Oct 16 '18 at 08:07
  • I edited my answer, you are trying to access an index array that doesn't exists. – Gonzalo Oct 16 '18 at 09:05
  • now it only says The uploaded file type is not allowed! –  Oct 16 '18 at 09:09
  • Sry it didnt actually work, what I did was i moved the $prodId = ... line into the if as you showed me, it removed the undefined index error but it doesnt insert any data into the database now, the meaning was that i wanted to make it possible to create a "type" with and without and image using that class. –  Oct 16 '18 at 09:53
  • The only thing that changed is you are not calling ``$products->newType()``. I cannot guess what that call makes, and you where passing and invalid value ``$newfile['filename']``, you should not access ``filename`` before check it is correct. – Gonzalo Oct 16 '18 at 10:44
  • hate to keep bugging you with this but do you know how i can get the class to work with my form? and is it bad practice to use the class? –  Oct 16 '18 at 10:54
  • What i mean is, now your data is not been saved into db, why does it before? where are you saving your data? You just moved a broken line of code where it should be. I haven't read the whole class but if you could add a ``filename`` index to your error returns. – Gonzalo Oct 16 '18 at 11:00
  • This is what i got when i submit without a picture Notice: Uninitialized string offset: 0 in C:\xampp\htdocs\proceskontrol\classes\FileUploader.php on line 60 The uploaded file type is not allowed! –  Oct 16 '18 at 11:07
  • line 60 is this if(!in_array($this->currentFile['type'][0], $this->mimetype)){ return [ 'success' => false, 'msg' => "The uploaded file type is not allowed!" ]; } –  Oct 16 '18 at 11:08
  • the newType in the if statement is a method i made, it looks like this,public function newType($post, $files) { $newfile = $files; return !empty($newfile) ? $this->db->lastId("INSERT INTO type_tb (name, image) VALUES (:name, :image)", [ ':name' => $post['name'], ':image' => $newfile ] ) : $this->db->lastId("INSERT INTO type_tb (name) VALUES (:name)", [ ':name' => $post['name'] ] ); } –  Oct 16 '18 at 11:13