Uploading Image with PHP from non-root folder

I’ve got the basics of how file uploads in PHP work. Once the submit button has been clicked, I grab the important stuff like the file size and file extension and check to make sure the user isn’t uploading anything too big or weird. After that, you give the file a new name, then move it into a folder called “uploads” located in your root folder.

All resources I’ve found online say to use the move_uploaded_file() command to move the uploaded file from its temporary location ($_FILES['file']['tmp_name'] ) to that uploads folder. The problem is, all those resources give examples of rather small projects with all files located right in the root folder. In my case, the scripting file is not located directly in the root folder but within a folder called scripts in the root folder.

- MyProject
   - pages
   - scripts
      - function.php
   - style
   - uploads

I’ve tried calling that move_uploaded_file() function with the destination as "uploads/ and as "../uploads/" (with the two dots in front) but neither work.

$fileNameNew = uniqid('', true).".".$fileExt;
$fileDestination = "../uploads/".$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);

(Note: In the snippet above, $fileExt is the file’s extension such as “jpg” and $fileTmpName is the temporary location of the file.)

Is there something special I have to do to get the right relative location of the uploads folder?

Well, the folder structure in your website is based on the root folder. Whenever you want to START at the ROOT folder, you use “\”… That is ALWAYS your root. So, to get to a folder inside the root folder if it is called uploads, it would be " \uploads\ "… If you want to back-up one folder, you use " …\ " to get to the folder above. If you are in scripts folder you show above, then, " …\uploads\image-name.jpg " should work.

How is this function.php file being accessed? Is the post method form’s action attribute to this file, i.e. scripts/function.php, meaning you are making a http request to the file, or are you requiring this file into a main .php file? If you are requiring this file into a different php file. the php code in fuction.php is being executed in the context of the main php file and the current working directory will be that of the main file, not where the function.php file is located at on the disk.

Do you have php’s error_reporting set to E_ALL and display_errors set to ON so that php would help you by reporting why the move_uploaded_file() statement is failing? In those cases where the path may have been correct, you could be getting a permission error instead.

Sponsor our Newsletter | Privacy Policy | Terms of Service