I have a cron job that runs a PHP script and creates files (images). But the cron job is running as me (being me my own username), not apache, nobody, httpd, www... and all the files created belongs to this user.

If I run the the same script through a browser, it runs as apache. I've tested it with whoami and checked the file permissions.

The problem is that if I develop an web-interface to remove files (which is how users/admin will be able to manage the images), it will run as apache and it won't be able to remove the files, as apache is not the owner nor belongs to the same group as me.

What would be the correct way to deal with this?

  • Add me to apache group or the other way around?
  • Save the files with permission 0777? This looks 'ugly'
  • Try to run the cron job as apache? How?

There are different solutions:

  1. Add your user to apache group www-data, nobody, or whatever it is called on your system. You need also to grant the group write permission.
  2. Run the cron job under apache user. This can be done using a command like: sudo su apache_user -c "crontab -e". However, this may not work depending on whether it is allowed to switch to apache user and add cron jobs for apache_user.

I think point 1 should be better.

  • 2
    I believe the contrary: It is a bad idea to mix users. Also, you don't need to use su there.
    – jankes
    Feb 26 '12 at 19:31
  • I did the first option. However, in the PHP script it must be mkdir('dir', 0775) and then chgrp('dir', 'apache'). Then both users can read/write.
    – rlcabral
    Feb 26 '12 at 21:58

It's best run the cron job as your apache user:

sudo crontab -u apache_user -e

This is a cleaner solution compared to running the job as you, because what belongs to apache should stay such. Mixing of users will bring mess and could produce problems at some point.

  • That would be the ideal. However, I don't have root access. I would have to contact my hosting every time I wanted to add/edit a cron job. If it was not for that, you answer would be the accepted answer.
    – rlcabral
    Feb 26 '12 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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