PHP - Create a folder and save an image to that folder? Then display that photo?

image, php, upload

Solution

You need to create the directory before you can move files into it. You can use the file_exists function to check on the directory first and then create it of needed:

if (!file_exists('path/to/directory')) {
  mkdir('path/to/directory', 0777, true);
}

You may prefer other permissions.

Problem

This seems like a big question, and it is, but the majority is done but I'm lost in actually getting where I want to be. I have the upload form ready and it works, it saves it to a folder named upload, but I need it to create a folder depending on the hotel name that is saved in my session. This is displayed on the page to tell users what session they are on. So now when they save I need it to create the folder named after it to save it to that directory. So here is the code for the HTML : ``` <span class="prettyFile"> <form id="form" action="assets/php/upload.php" method="post" enctype="multipart/form-data"> <div class="fileupload fileupload-new" data-provides="fileupload"> <div class="input-append"> <div class="uneditable-input span3" style="margin-top: -3px;"><i class="icon-file fileupload-exists"></i> <span class="fileupload-preview"></span></div><span class="btn btn-file btn-success"><span class="fileupload-new">Upload File</span><span class="fileupload-exists">Change</span><input type="file" name="file" /></span><a href="#" class="btn fileupload-exists btn-success" style="margin-top: -3px;" data-dismiss="fileupload">Remove</a> <button type="submit" name="submit" class="btn btn-primary fileupload-exists" value="Upload"><i class="icon-cloud-upload"></i> Upload</button> </div> </div> </form> </span> ``` And here is the PHP: ``` <?php $allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = end($temp); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 10000000) && in_array($extension, $allowedExts)) if (file_exists("upload/". $_SESSION['curHotelName'] . "/" . $_FILES["file"]["name"])) { echo "<script language='javascript'>\n"; echo "alert('This file exists! Please select a different file.'); window.location.href='https://hotelmobidev.jvgames.com/profile';"; echo "</script>\n"; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/". $_SESSION['curHotelName'] . "/" . $_FILES["file"]["name"]); echo "<script language='javascript'>\n"; echo "alert('Success!'); window.location.href='https://hotelmobidev.jvgames.com/profile';"; echo "</script>\n"; } ?> ``` I'm still messing with it but if someone can bump me in the right direction that would be awesome! Thanks guys!

Original source