Create folder and upload images in php / codeigniter

I have a simple image upload form on my website where users can upload multiple images at once. I want my images to be organized in a folder based on month and year in the following format: MONTH-YEAR, so whenever I start a new upload, I first check if this folder exists or not and create it if it doesn't exist.

The problem is that if the folder doesn't exist for the current month and I try to upload an image, the folder representing that current month is created correctly, but then the image doesn't load. But if the folder already exists, all images can be uploaded without any problem. Here is my code:

    $folderName = date('m-y');
    $pathToUpload = './uploads/photos/' . $folderName;
    if ( ! file_exists($pathToUpload) )
    {
        $create = mkdir($pathToUpload, 0777);
        $createThumbsFolder = mkdir($pathToUpload . '/thumbs', 0777);
        if ( ! $create || ! $createThumbsFolder)
        return;
    }

    $imgName= uniqid('', TRUE);
    $config['upload_path'] = $pathToUpload;
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '9999';
    $config['file_name'] = $imgName . '.jpg';

    $this->upload->initialize($config);
    $upload = $this->upload->do_upload("Filedata");

      

Any ideas why the download isn't working the first time?

+3


source to share


2 answers


Don't listen to these guys. You are logical - if it mkdir()

returns false or time, then it should fail.

However, as mazzzzz suggests, I would throw an exception in this case, instead of returning false.

I would do this too (rather than multiple calls to mkdir()

):

<?php
mkdir($pathToUpload . '/thumbs', 0777, TRUE);

      



This will recursively create all the missing directories needed to create the thumbs folder, and I suspect you fail anyway.

If this is not the case, then for some reason you do not have privileges, which seems unlikely if you can upload files.

Also, you may have a problem with the statistics cache. Try to run clearstatcache()

beforedo_upload()

+3


source


To answer the "Jumping Frog" question in the comments, it looks like you can go back to uploading because you're not throwing an error, but just fail if you think the folders aren't being created even though they are.

If you understand that $create

and $createThumbsFolder

must be true for the program to continue, you can check the logic of the statement if

. If mostly specified if (!true || !true)

, which means if (false || false)

it can be simplified to if (true)

, because if either false, it also returns true. Where, as a solution, Frog says it is if (!(true && true))

simplified to if (!true)

simplified to if (false)

so that if both values ​​are desired (and expected), they are not returned.



Hope it helps explain the logic error a bit, good luck with the bootloader!

PS Don't bother!

0


source







All Articles