简体   繁体   中英

Using Crontab to run a php script

I've got a PHP script that simply e-mails me a test message. If I go into my webserver cPanel I can create a cronjob that runs the script every 10 minutes and it works perfectly.

I manually schedule the cron job in cPanel using the following settings:

10 * * * * php -q /home1/user1/public_html/mail.php

Again the above works fine, but when I try to create the cron job via PHP instead of cPanel it never runs. When I check the cPanel to see if the job was actually created by my php script it DOES show up. All the settings that show up in cPanel are correct, it just doesn't run the script.

This is the PHP code I'm using to create the cron job:

$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.'10 * * * * php -q /home1/user1/public_html/mail.php'.PHP_EOL);
echo exec('crontab /tmp/crontab.txt');

I imagine it could be a permission issue or something like that? Not really sure why the job works when I create it, but doesn't when PHP creates it.

PHP shell scripts, eg cli/cron jobs, STILL require a <?php tag. eg

#!/usr/bin/php
<?php
$output = blah blah blah

Remember that there's no such thing as a "php script". There's only files that have PHP code blocks within them. Without an opening <?php tag block SOMEWHERE in the file, the PHP execution engine will never kick in, even though the file will have been processed/parsed by PHP.

Without <?php , the file's contents will simply be treated as plaintext output.

Ended up figuring this out...I'm sure what was wrong with the php code I was using above but it seems that was somehow causing the execution failure.

I'm now using the code below and the job schedules and actually runs :)

exec('echo -e "`crontab -l`\n10 * * * * php -q /home1/user1/public_html/mail.php" | crontab -');

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