“move_uploaded_file gives “failed to open stream: Permission denied”

The full error is: Warning: move_uploaded_file(…/public_html/download/download.sql): failed to open stream: Permission denied
Running LAMP on Ubuntu 18.04, Apache 2.4, PHP 7.23
Steps I’ve taken:

  1. Ensured I’m a member of the www-data group
  2. Run “sudo chown -R www-data:www-data /var/www”
  3. Ensured that download and temp folders exist under /var/www/html and that they have the correct permissions.

My code follows:

$target_dir = "../public_html/download/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;

if(isset($_POST["submit"])) {
   
    if (file_exists($target_file)) {        // Check if file already exists
        echo "Sorry, file already exists.";
        $uploadOk = 0;
         }
    else  {        // if everything is ok, try to upload file 
      if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
         echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } 
      else {
         echo "Sorry, there was an error uploading your file.";
        }
    }
}

I don’t know where to go from here. Any help is appreciated.

Larry

Did all that before asking for help. I was already a member of www-data and already made sure www-data was the owner of /var/www and all subfolders and files. I also made sure that file permissions were set to 755. I issued a “sudo systemctl restart apache2.service” just to be sure.

I believe the problem might be the file structure under /var/www. Is there supposed to be a directory for website and under that the download and temp folders?

It’s possible that you gave the permissions to the wrong directory. The www directory is the symlink, the public_html directory is the real location.

I’m the owner of public_html and a member of www-data. Permissions were already set to 775. Should I set www-data as the owner?

  1. Check apache process owner: $ps aux | grep httpd . The first column will be the owner typically it will be nobody
  2. Change the owner of images and tmp_file_upload to be become nobody or whatever the owner you found in step 1.
$sudo chown nobody /var/www/html/mysite/images/

$sudo chown nobody /var/www/html/mysite/tmp_file_upload/
Sponsor our Newsletter | Privacy Policy | Terms of Service