Php – Using crontab to delete tmp folder files created by apache user

apache-2.2cronpermissionsPHP

Currently I have it set up such that users can download zip files from my site, and they're stored in /tmp/zip_file_dir/. The PHP script first downloads them from my CDN using ftp_get() and then places them in that folder such as /tmp/zip_file_dir/random_hash_folder/file_here.zip. Then I simply use readfile() to initiate the download for the user. That all works fine.

However, I then later use a cronjob to clear this folder out (the script deletes the downloads after readfile(), but if the user cancels the download script the files aren't deleted by it hence the point of the cronjob to clean these up).

The file_here.zip file has the permissions -rw-r--r-- with the owner apache. Each random_hash_folder in zip_file_dir has the permissions drwxr-xr-x with the owner apache. The cronjob simply scans the zip_file_dir and uses rmdir() and unlink() to delete the files.

The cronjob is run by a user with sudo access to the server (i.e. more permissions and abilities than the apache user). However, I keep getting PHP "Permission denied" notices when trying to delete the files.

I've tried added the sudo user running the cron job to the apache and nobody groups as mentioned elsewhere in some of my Google research, but that hasn't brought me any luck.

Any ideas how I get this cronjob to delete those files?

Edit: I am using RHEL.

Best Answer

You don't need any more permissions and abilities than the Apache user. Since the apache user created those files, the apache user can destroy them. The apache user seems like the most appropriate user to me.

You can either put your cron job in the apache user's crontab ( sudo crontab -u apache -e) or run the job from root's crontab as the apache user:

1 5 * * * su apache -c "/path/to/cleanup_script.php"

Choose the option that helps you keep track of your cron jobs the easiest.