I have code that successfully can upload a Word file onto my server. The problem is that it saves it in a subfolder of the location that the php file is in, so it is publicly available if someone puts the directory and filename. I want to save the file in a non-public folder but I can’t figure out what the path is. I am on a shared server with cpanel on it.
$target_dir = "uploads/";
$file_name = basename( $_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". $file_name. " has been uploaded. <br>";
} else {
echo "Sorry, there was an error uploading your file.";
exit;
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
The files are currently being saved to “/home/myusername/public_html/resume/uploads” but I want to save it to “”/home/myusername/uploads”. I only know how to save the files to folders within the folder that the PHP program is in. I know this is probably really easy but I have been Googling this for a while and can’t find the answer.
2
Answers
Just change this:
to this:
You can save in any directory you like (provided that it exists and the process has permission to write to it). All you have to do is specify the directory.
The thing to remember is that PHP gets its bearings from the whole operating system, not the web root. That means that either you will need to know the absolute address of the folder, or you’re stuck with navigating up and down containing folders.
Given your question, the location would be:
Given your example, I assume that the script is running inside the
resume
directory. The first..
moves up topublic_html
and the second tomyusername
. From there it’s down intouploads
.An alternative is to use an absolute address:
In both cases, you will need to make sure that PHP has write permissions to the folder in question.