简体   繁体   中英

Execute PHP in cron job on centos

I needed help on my cronjob experiment, im unable to accomplish what i wanted. below are the things I did.

  1. Create a php file inside /var/www/html/bob/test/index.php
  2. Set permission rights of the directory and file to executable (0777)
  3. Specify a cronjob

My index.php

<?php 
$myfile = fopen("testfile.txt", "w");  
?>

My various tested parameters for crontab -e which didn't work

*/1 * * * * root /usr/bin/php /var/www/html/bob/test/index.php
*/1 * * * * root /var/www/html/bob/test/index.php
*/1 * * * * root php -q /var/www/html/bob/test/index.php
*/1 * * * * root /var/www/html/bob/test/index.php

looking at some of my /var/log/cron I dont see any error indication.

Sep 6 15:55:01 localhost CROND[4866]: (root) CMD (root /var/www/html/bob/test/index.php)
Sep 6 15:56:01 localhost CROND[4872]: (root) CMD (root /var/www/html/bob/test/index.php)
Sep 6 15:57:01 localhost CROND[4878]: (root) CMD (root /var/www/html/bob/test/index.php)

Lastly, when i run my php via #php /var/www/html/bob/test/index.php the code executes fine and creates that textfile.

You need to remove root from your cronjob. The log is showing it's trying to execute a program called root with /var/www/html/bob/test/index.php as a parameter.

Instead, use the following as your cronjob:

*/1 * * * * /usr/bin/php /var/www/html/bob/test/index.php

This answer states that if you want to set the user for a cronjob to be run, you have to edit /etc/crontab directly, not by using crontab -e .

1 * * * * /usr/bin/php /var/www/html/bob/test/index.php

if this not working, so you have a probleme of permission , try to use chown and chmod for giving the right permission

and for $myfile = fopen("testfile.txt", "w"); try to use the absolute path for the file testfile.txt like :

 $myfile = fopen("/home/xxxx/testfile.txt", "w"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM