I have a simple image upload form on my website where users can upload multiple images at once. I want to have my images organized in folder based on the month and year in the following format: MONTH-YEAR, so each time new upload starts I first check whether that folder exists or not, and create one if it doesn't exists.
The problem is that if the folder doesn't exists for the current month and I try to upload an image, the folder, representing this current month, is created properly, but then no image is uploaded. But if the folder already exists all the 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 upload doesn't work for the very first time?
Don't listen to these guys. You're logic is fine--if mkdir() returns false either time, then it should fail.
However, as mazzzzz suggests, I would throw an exception in that case, rather than returning false.
I would also do this (rather than multiple calls to mkdir()):
<?php
mkdir($pathToUpload . '/thumbs', 0777, TRUE);
This will recursive create all missing directories needed to create the thumbs folder, which I suspect is where you're failing anyway.
If that's not the case, then somehow you don't have privileges, which seems unlikely if you can upload files.
Additionally, you might have a stat cache problem. Try running clearstatcache() before do_upload()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With