skip to Main Content

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


  1. Just change this:

    $target_dir = "uploads/";
    

    to this:

    $target_dir = "../../uploads/";
    

    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.

    Login or Signup to reply.
  2. 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:

    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "../../uploads/$target_file");
    

    Given your example, I assume that the script is running inside the resume directory. The first .. moves up to public_html and the second to myusername. From there it’s down into uploads.

    An alternative is to use an absolute address:

    move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "/home/myusername/uploads/$target_file");
    

    In both cases, you will need to make sure that PHP has write permissions to the folder in question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search