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

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

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.

Related

Setting up a Cron Job on CPanel to executes a PHP script

As implied in the title, the Cron Job is supposed to execute a php file (update.php, to be specific). The php file then writes to a csv file stored in the same directory.
I have the time set to * * * * * so that it executes every minute. The command is written as follows:
php -q /home//public_html/wallboard/update.php
I don't believe this is causing any errors, though it also doesn't seem to write to the CSV file. When I visit update.php in a browser, however, it executes and writes to the CSV file immediately. I'm not experienced with Cron Jobs and I'm sure there's an issue, but I don't know what exactly that issue is. Let me know if you have suggestions/questions. Any help is appreciated!
Current Command:
* * * * * usr/bin/php -q /home/<user>/public_html/wallboard/update.php
update.php:
<?php
include('lib/HelpDeskView.php');
include('lib/WallboardDisplay.php');
include('helpdesk.csv');
$helpdesk = new HelpDeskView();
$text="\r\ntest,test,test";
file_put_contents( "helpdesk.csv" , $text, FILE_APPEND);
Since your script resides in your public_html directory you can use wget for your Cron Job
wget -O - -q https://yoursite.com/wallboard/update.php
-O - output is written to the standard output in this case it will go to the email address you specify in CPanel
-q quiet mode
IMHO the best way is to contact support and ask them about command line syntax.
This is how I'm doing it at my linux server using cPanel.
This runs script.php which is stored in public root. Course, replace <username> in command line with your username.
At another server I'm using same command line with /usr/bin/php instead of php at the beginning of line, but I'm aware that not all servers use same command line. Some require php-cli in command line instead of php, some don't "like" -f argument, etc. So try various combinations.
To find more suggestions check out this SO topic too: Run a PHP file in a cron job using CPanel
Important thing: When trying different commands wait at least a minute (this case) to see if it works because Cron doesn't fire your script immediately.
Try to execute the same command in PHP CLI and check if it gives you any error, you might be missing some libraries or references required for CLI execution.
/usr/bin/php -d register_argc_argv=On /home/USERNAME/public_html/DOMAIN/artisan AMIR:HOME

php execute crontab script every 1 minute

as part of a php-slim web application, in my init.php file I require a Crontab.php which contains the following code:
<?php
// clears any existing crontab jobs first
exec("crontab -r");
$ctCommand = '"*/1 * * * * php ./ProcessCycleTimeData.php"';
exec("(crontab -l 2>/dev/null; echo " . $ctCommand . " ) | crontab -");
exec("crontab -l");
?>
When I run the commands manually, the job gets added and I can see it being recorded, however it doesn't seem to run. However, when I run php ./ProcessCycleTimeData.php it works fine. Any ideas where to troubleshoot this?
I'm looking into the error logs, and every minute I get the following log:
crontab: no crontab for daemon
You can use crontab -e to edit the crontab, this will open your default editor (generally vi if other is not set).
Edit the crontab for the user you need this script to run, and add a line as:
*/1 * * * * php ./ProcessCycleTimeData.php
This means
Every one minute
Note:
The PHP snippet you provide is trying to edit the crontab and add the above line. However it might be failing due lack of permission.
I managed to get it working. My solution was to check if the crontab was actually running by appending the crontab job with >>/tmp/auto-update.log 2>&1 which allowed me to further investigate the issue.
I found that the crontab was indeed running, but as a different user (hence why when I was manually calling crontab -e I could not see the job since I am calling it as my own username.
The crontab was also actually invoking my PHP script, where I could then find out the errors in the auto-update.log, which happened to be due to incorrectly stating the require paths.

Run a php file in a specified timeframe

I have a php script, let's say fetch.php which will pull data from other database and insert those data to another database, How do I run the script automatically maybe via command line, let's say I want it to run Everyday at 3pm? Something like a cron.
Here is the cron rule you should add:
00 15 * * * php fetch.php
Read more here: Running a script every day using a cron job
If you are on Windows, you can make use of Windows Task Scheduler.
Here is the link: http://windows.microsoft.com/en-US/windows/schedule-task#1TC=windows-7
Using php from command line is not that hard. Start the fetch.php file like this:
#!/usr/bin/env php
<?php
// You have the command line arguments available as
$scriptName = $argv[0];
$firstArg = $argv[1];
// Add PHP code here :)
// If an error occurs, exit the script with an error code:
if($someError) exit(1);
After saving, set execution rights:
$ chmod 755 fetch.php
Then add the script to the crontab. There are many ways, control panels like Plesk and cPanel have a web interface for example, but here's the command line version:
$ crontab -e
Add to the file:
0 15 * * * /path/to/fetch.php
Save, and you're done.

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, e.g. cli/cron jobs, STILL require a <?php tag. e.g.
#!/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 -');

what to change in my php script for the cron job to work

Ok I have been looking into cron jobs for hours, checked every post here, looked in google but I just do not understand how it works.
I have set up a cron job using my path 1 * * * * /home/myuser/domains/mysite/public_html/live.php I have also tried /home/myuser/public_html/live.php
Nothing seems to be working.
Do I have to add something in the php file (live.php)? That is the code that has to be executed. The code itself works.
I know you will all think that I am lazy but I really can't figure this out.
*.php is regular script file which, as any other scripting languages like i.e. perl requires interpreter to run. So if you want to run your script from command line you have either call interpreter and give it your script file as argument, like:
$ /usr/bin/php myscript.php
And that's it - it should run.
Or (if working using linux/bsd) add as very first line of your PHP script file:
#!/usr/bin/php -q
which tells shell, where to look for interpreter for this script file. Please ensure your PHP is in /usr/bin folder as this may vary depending on the distro. You can check this using which, like this:
$ which php
/usr/bin/php
if path is right, you yet need to set executable bit on script file so you'd be able to try to "launch it":
chmod a+x myscript.php
This will make it behave as any other app, so you'd be able to launch it this way:
/full/path/to/myscript.php
or from current folder:
./myscript.php
And that's it for that approach. It should run.
So your crontab line would look (depending on the choosen approach):
1 * * * * /full/path/to/myscript.php
or
1 * * * * /usr/bin/php -q /full/path/to/myscript.php
And you should rather use "0" not "1", as 1st minute in hour is zero, i.e.:
0 * * * * /usr/bin/php -q /full/path/to/myscript.php
EDIT
Please note cron working directory is user's home directory. So you need to put that into consideration, which usually means using absolute pathes. Alternatively you'd prepend your call with cd <script working path> && /usr/bin/php -q /full/....
Maybe
1 * * * * php /home/myuser/domains/mysite/public_html/live.php
You need to make your script executable with chmod on the command line.
Furthermore you need something like this:
#!/usr/bin/php
<?php
// here comes your code
?>
This is required to tell the command line how to execute the file.
Note: this will only work if your php binary is located in /usr/bin/php

Categories