How can I make a cron to execute a php script?

让人想犯罪 __ 提交于 2019-12-25 03:51:58

问题


I want execute a php script each five minutes at my server, it is a php script which works fine alone, I tried since my browser and since console using "php -f php_file.php". But I need execute it automatically every days. I was searching on Google and here to make it but any solution worked for me:

First I edit my crontab and I also restart the cron to make sure that it was updated correctly.

*/5 * * * * /usr/bin/php /var/www/myscript.php

and I tried the following too:

*/5 * * * * /usr/bin/php -f /var/www/myscript.php

I made the script executable too, review my system log (where I can see that my cron is executing correctly, but it doesn't execute php script) and I also try to redirect the output of cron to a file, but it leaves the file empty. Anyone can help me?

Best regards


回答1:


You were on the right track by making your script executable.

Do it again if needed

$ chmod +x script.php

Add this to the very top of the file:

#!/usr/bin/php
<?php
// here goes your script

you can test if the script executes by running it like this

$ ./script.php

set-up your cron job like below to set-up some logging but make sure you output something from your script, use print or echo and a relevant message.

*/5 * * * * /var/www/script.php >> /var/www/script.log 2>&1

we are redirecting both standard output and errors into the script.log file.

check every 5 min for activity.


Update:

Try this in your php script

$file = '/var/www/script.txt';
for($i=0;$i<9;$i++){
    $entry = date("Y-m-d H:i:s") . " " . $i . PHP_EOL;
    echo $entry; // this should write to the log file

    file_put_contents($file, $entry, FILE_APPEND | LOCK_EX); 
    // and this should write to the script.txt file
}

basically we are giving the full path to the file and passing the FILE_APPEND flag so we don't overwrite every time.

Run the script and check if the file is created, the default behavior is to create the file if it doesn't exist.



来源:https://stackoverflow.com/questions/33099274/how-can-i-make-a-cron-to-execute-a-php-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!