Question

In php I do the following:

exec('remove_file.sh', $output, $return);

where remove_file.sh is the following script:

#!/bin/sh
rm -f /tmp/test.pdf

I verified that this script is run by www-data and test.pdf is owned by myuser but with 666 (rw-rw-rw-) permissions. /tmp is owned by root and has 666 permission.

The script returns 1 (general error) without any output.

If I try from a terminal:

sudo su www-data -c 'rm -f /tmp/test.pdf'

I get:

cannot remove `/tmp/test.pdf': Operation not permitted

How can I remove this file from a php script?

Was it helpful?

Solution

You probably have to make sure www-user has write permission to the directory, as well as the file. This depends on the filesystem, but most require this for rm or mv operations.

So chmod 777 /tmp should do the trick.

Edit: The above may not be a secure way to accomplish the desired availability. Depending on your setup, a more thorough way to accomplish this would be to add www-user to the users group (assuming myuser primary group is users), then set the /tmp directory to rwx for user & group.

# usermod -g users www-user
# chmod 770 /tmp

Allowing everyone to read, write and execute in /tmp is not suitable for multi-user or unsecured boxes, and whilst it may work fine on a well secured server, you are giving a lot of access to anyone who compromises the box.

An even better alternative is to have php upload files to a more local directory instead of using bash scripts using $_FILES and then use PHP again to delete them with unlink. This way all files will belong to www-user. Remember that it's essential to validate files thoroughly before allowing uploads to prevent attacks via c99 and similar malware.

EDIT (from OP):

Though the security issues do not apply in my case, I completely agree with the previous edit. Using /tmp was the lazy way out. But the real problem was that I tested creating a file under my own user and then continued testing from www-data. Under the default permissions of /tmp you cannot (rightly so) delete another users file nor overwrite it. This resulted in various issues, not only with rm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top