Issue
What is the solution to delete the files outside of web dir? It doesn't delete the files.
Script will be accessed via web browser (only admins).
For example:
PHP located at: /var/www/html/delete_xx_phones.php
-rwxr-xr-x 1 root root 592 Mar 13 17:18 delete_xx_phones.php
delete_xx_phones.php
code look something like this:
foreach(glob("/path/004*-phone.cf") as $file) {
unlink($file);
}
Files in /path
-rw-r--r-- 1 root root 346 Mar 13 17:15 004aaaa-phone.cf
-rw-r--r-- 1 root root 346 Mar 13 17:15 004bbaa-phone.cf
Solution
PHP scripts often run as user other than root, as they typically are executed by httpd. Since your files are set to have write permissions only for the root user, that's not going to work out.
If you cannot permanently change the ownership or write permission of the files, you could consider writing a very short script and executing it with elevated permissions (using sudo
or the suid bit) instead of calling unlink()
on PHP.
For the suid approach, write a simple script in Perl (may require perl-suidperl package installed), which deletes the filename passed as an argument:
delete-file.pl:
#!/usr/bin/perl -wT
# This is VERY insecure, so if you use it, make sure you modify it
# to filter the filenames before putting the script on production
# machines
unlink $ARGV[ 0 ];
Make sure the file is owned by root (chown root delete-file.pl
) and then run chmod 6711 delete-file.pl
to set its SUID bit. After that the file will always execute as root.
Then in your PHP script, you'll just need to run exec( "/path/delete-file.pl $filename" )
(consider shellescapearg()
for safety) and your files should start deleting.
(Note that I'm specifically using Perl here because Bash traditionally ignores the suid bit.)
If you feel more comfortable with using sudo
, then just write a script similar to what is described above (Bash will work too) and just add it to /etc/sudoers
. You can then do something along the lines of: exec( "/usr/bin/sudo /path/to/delete-file-script $filename" );
to run the script with elevated permissions.
Answered By - Salieri Answer Checked By - Clifford M. (WPSolving Volunteer)