Question

I am uploading multiple images within a single category and I would like to store each group of images in a unique directory within my 'images/' directory as follows:

'images/unique_category/image1.jpg'

I have the following code but it is not creating a directory. I suspect it has something to do with setting the recursive parameter as 'true' which I believe I have done. Am I using the mkdir function incorrectly?

Thank you!

$unique_directory = "../images/".$_POST['item_name'];
if (is_dir($unique_directory)
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  $unique_directory."/".$_FILES["file"]["name"]);
  echo "Stored in: " . $unique_directory."/".$_FILES["file"]["name"];
  }
else
  {
  mkdir($unique_directory, 0777, true);
  move_uploaded_file($_FILES["file"]["tmp_name"],
  $unique_directory."/".$_FILES["file"]["name"]);
Was it helpful?

Solution

Here, give this a try. I tested it on my (hosted) server and it works. Yet, I tested it by placing the files in the root of it, and used images instead of ../images for the $unique_directory variable.

I also used the chmod command apart from the other function, because the other method did not work.

N.B.: If possible, try changing 0777 to 0755, because using 0777 is not the safest setting.

<?php
$filename = $_POST['item_name'];
$unique_directory = "../images";

if (!is_dir($unique_directory . '/' . $filename)){

    mkdir($unique_directory . "/" . $filename);

    chmod("$unique_directory" . "/" .$filename, 0777);
}

if (is_dir($unique_directory))
  {
  move_uploaded_file($_FILES['file']['tmp_name'], $unique_directory . "/" . $filename . "/" . $_FILES['file']['name']);
  echo "1) Stored in: " . $unique_directory . "/" . $filename . "/" . $_FILES['file']['name'];
  }

else
  {
  move_uploaded_file($_FILES['file']['tmp_name'], $unique_directory . "/" . $filename . "/" . $_FILES['file']['name']);
  echo "2) Stored in: " . $unique_directory . "/" . $filename . "/" . $_FILES['file']['name'];
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top