Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a problem where I am trying to copy a file that is generated on a server drive that I have mounted using the php exec command. However, the command doesn't work (although the return status is 1) when called from a web-page.

$src = "/mnt/...";
$dest = "/var/www/...";
exec("cp $src $dest");

I have tried printing out the command to make sure it is correct, and it is. I have also tried making sure the file exists before attempting to copy it and it is.

if (file_exists($src)) {
    exec("cp $src $dest");
}

Copying the command directly into the terminal works.

$ >cp /mnt/... /var/www/...

I've also tried using the php command line tool to run the exec command and that also works.

$ >php -r 'exec("cp /mnt/... /var/www/...");'

I have also tried using shell_exec as well, with the same results.

share|improve this question
1  
This is probably because php is being run under a different user on the system, and that that user does not have the rights to do that action on those files. You could look into sudo to perform this –  Frank Aug 27 at 18:15
 
Wouldn't I get a status code of 0 then? –  BLenau Aug 27 at 18:16
 
Last time I had this error, I didn't think of looking at the status code so I can't be sure of that, sorry. But using sudo did fix my problems –  Frank Aug 27 at 18:32
1  
I bet PHP doesn't have permissions to either copy the file from source, or it doesn't have permissions to copy to the destination. Or it could be both. –  Ryan Naddy Aug 27 at 18:33
1  
Try to check is_writable($dest). Chances are it's false, which means, as others have said, the PHP user cannot write to it. Usually PHP is ran as the apache (www-data) or nobody user. Run echo exec("whoami"); to see the user it's running as. –  Rocket Hazmat Aug 27 at 18:44

2 Answers

You can add the second parameter to help debug, $output will display what the cp command is doing, whether it be an error or not.

I would also recommend placing quotes around the files, just in case something with a space gets in there.

$src = "/mnt/...";
$dest = "/var/www/...";
exec("cp '$src' '$dest'", $output, $retrun_var);

var_dump($output, $retrun_var);
share|improve this answer

I had a similar issue a while ago. It was essentially what all the commentators are saying. The user/permission of the web server are restricted, but also the shell environment that is being used and/or the PATH environment variable.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.