Search code examples
phpapachewebserver

I can not copy a file in PHP to another directory out of /var/www in my apache2 web server


i want to copy a file in php. But, I am having a problem that is not a syntax one. knowing that i already did the chmod command for the file to be able to copy and changed !! here is my codes:

this code is not working !

<?php
    $file = 'example.txt';
    $newdir  = '/home/Dell/Desktop';
    $newfile = 'example.txt.bak';

    echo "Trying to copy  $file...<br><br>  ";

    echo' loading .... <br>';
    echo' loading .... <br>';

    if (!copy($file, $newdir.'example.txt.bak')) {
        echo "failed to copy $file...\n";
    } 
    else {
        echo' the file should be in'. $newdir;
    }


    //this code is working cause I have changed the location to /var/www/ directory!!!

    $file = 'example.txt';
    $newdir  = '/var/www/';
    $newfile = 'example.txt.bak';

    echo "Trying to copy  $file...<br><br>  ";

    echo' loading .... <br>';
    echo' loading .... <br>';

    if (!copy($file, $newdir.'example.txt.bak')) {
        echo "failed to copy $file...\n";
    }
    else {
        echo' the file should be in'. $newdir;
    }
?>

I have tried:

 move_uploaded_file()
 copy()
 rename()

And nothing works !!. please please help here.


Solution

  • It's not PHP, it's Apache. Your Apache user does not have access (or simply, not allowed) to write to the directory given.

    Here's the solution:

    1. Find your Apache group by executing awk -F= '$1 == "export APACHE_RUN_GROUP" {print $2}' /etc/apache2/envvars. If you are in ubuntu and using Apache2, the default user and group would be www-data.
    2. Chown the target dir recursively (in your case, it would be /home/Dell/Desktop) by executing sudo chown :www-data /home/Dell/Desktop -R
    3. Chmod the target dir recursively (again, in your case, it would be /home/Dell/Desktop) by executing sudo chown :www-data /home/Dell/Desktop && sudo chmod 775 /home/Dell/Desktop && sudo find /home/Dell/Desktop -type d -exec chmod 775 {} \; && sudo find /home/Dell/Desktop -type f -exec chmod 664 {} \;