Hi digital,
I have done the tests. I give you the result i got. It may be useful info for you to direct me what to do.
Thanks
<?php
$result = file_put_contents('/var/www/toy/test.txt', 'hi');
var_dump($result);
?>
gives this error
Warning: file_put_contents(/var/www/toy/test.txt) [function.file-put-contents]: failed to open stream: Permission denied in /var/www/in.php on line 2
bool(false)
You can see here that PHP cannot write to that folder.
ls -l /var/www/toy/
prints info given below
-rw-r--r-- 1 ubuntu ubuntu 731 2009-09-16 15:56 index.php
-rw-r--r-- 1 ubuntu ubuntu 731 2009-09-16 15:56 index.php~
-rw-r--r-- 1 ubuntu ubuntu 20576 2009-09-11 11:23 toy-11-09-2009_11:10:46.sql
The files in the folder are owned by ubuntu and group ubuntu.
-rw-r--r-- means user can read and write, group can read, world (anyone else) can read.
ie:
the groups are: user, group and world.
the access flags are: (r)ead, (w)rite, e(x)ecute
User Group World
- rw- r-- r--
var_dump(posix_getpwuid(posix_geteuid()));
prints info given below
array(7) {
["name"]=>
string(8) "www-data"
["passwd"]=>
string(1) "x"
["uid"]=>
int(33)
["gid"]=>
int(33)
["gecos"]=>
string(8) "www-data"
["dir"]=>
string(8) "/var/www"
["shell"]=>
string(7) "/bin/sh"
}
The PHP process belongs to the user "www-data".
The user "www-data" cannot write to the folder /var/www/toy/, since only the user "ubuntu" has write privileges to it.
You'll need to give www-data privileges to write to /var/www/toy/. The simplest way is it log in as "root" or "ubuntu", and chown /var/www/toy/ to the user www-data.
eg:
sudo chown www-data /var/www/toy/
Then you should be able to have PHP write to it.Note:
The reason you can write to that folder from the shell is because you're logged in as "ubuntu". Thus when you start mysqladmin, the process belongs to "ubuntu". However, when mysqladmin is started from PHP by Apache, the process belongs to the Apache user "www-data".
Another method:
What you can also do, to overcome problems like this is to create a script that will do the backups for you, and have the setuid flag set for that script. You can even write it in PHP.
eg:
#!/usr/bin/php
<?php
exec("/usr/bin/mysqldump -u root -h localhost toy > /var/www/toy/toy-`date +%d-%m-%Y-%H:%M:%S`.sql", $stdout $exit_status);
// just echo the output
echo implode("\n", $stdout);
if (!$exit_status) {
// something went wrong
exit($exit_status);
}
// all ok
exit(0);
?>
Note the shebang is needed:
#!/usr/bin/php
This tells the shell to run it though the PHP interpreter.
Say you save the file as:
db-backup.php
You must then invoke it as:
./db-backup.php
Now you have to set the setuid flag on the script, so that when it is executed, the process belongs to the file owner, instead of the parent process that started it.
eg:
su ubuntu
chmod ug+s db-backup.php
This means when db-backup.php is executed, the process will be owned by ubuntu.
Now to run your script from PHP started by Apache:
<?php
exec("./db-backup.php");
?>