How to Determine If a PHP File Is Loaded via Cron/Command Line

How to determine if a PHP file is loaded via cron/command line

If you have control over the cron or command, have you considered passing a command-line argument, and reading it with $_SERVER['argv'][0]?

* * * * *   /usr/bin/php /path/to/script --cron

In the script:

<?php
if(isset($_SERVER['argv'][0]) and $_SERVER['argv'][0] == '--cron')
$I_AM_CRON = true;
else
$I_AM_CRON = false;

Can PHP detect if its run from a cron job or from the command line?

Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually.

There are a lot of environment variables (in the $_ENV array) that are set when you run a script from the command line. What these are will vary depending on your sever setup and how you log in. In my environment, the following environment variables are set when running a script manually that aren't present when running from cron:

  • TERM
  • SSH_CLIENT
  • SSH_TTY
  • SSH_CONNECTION

There are others too. So for example if you always use SSH to access the box, then the following line would detect if the script is running from cron:

$cron = !isset($_ENV['SSH_CLIENT']);

PHP - How to know if PHP script is being run via a Cron

There is a php_sapi_name() function for that

Check if a php file command is already running on cron

If you want the php solution, the simple way is to create a lock file, each time script is executed , check if file exist then exit script, if not let script go to end. But i think it's better to use flock in cron instruction ;)

<?php
$filename = "myscript.lock";
$lifelimit = 120; // in Second lifetime to prevent errors
/* check lifetime of file if exist */
if(file_exists($filename)){
$lifetime = time() - filemtime($filename);
}else{
$lifetime = 0;
}
/* check if file exist or if file is too old */
if(!file_exists($filename) || $lifetime > $lifelimit){
if($lifetime > $lifelimit){
unlink($filename); //Suppress if exist and too old
}
$file=fopen($filename, "w+"); // Create lockfile
if($file == false){
die("file didn't create, check permissions");
}
/* Your process */
unlink($filename); //Suppress lock file after your process
}else{
exit(); // Process already in progress
}

Execute PHP script in cron job

Automated Tasks: Cron

Cron is a time-based scheduling service in Linux / Unix-like computer operating systems. Cron job are used to schedule commands to be executed periodically.
You can setup commands or scripts, which will repeatedly run at a set time. Cron is one of the most useful tool in Linux or UNIX like operating systems. The cron service (daemon) runs in the background and constantly checks the /etc/crontab file, /etc/cron./* directories. It also checks the /var/spool/cron/ directory.

Configuring Cron Tasks

In the following example, the crontab command shown below will activate the cron tasks automatically every ten minutes:

*/10 * * * * /usr/bin/php /opt/test.php

In the above sample, the */10 * * * * represents when the task should happen. The first figure represents minutes – in this case, on every "ten" minute. The other figures represent, respectively, hour, day, month and day of the week.

* is a wildcard, meaning "every time".

Start with finding out your PHP binary by typing in command line:

whereis php

The output should be something like:

php: /usr/bin/php /etc/php.ini /etc/php.d /usr/lib64/php /usr/include/php /usr/share/php /usr/share/man/man1/php.1.gz

Specify correctly the full path in your command.

Type the following command to enter cronjob:

crontab -e

To see what you got in crontab.

EDIT 1:

To exit from vim editor without saving just click:

Shift+:

And then type q!

Running PHP file using crontab

To execute devicecheck.php every 1 hour try the following:

Method A :: Execute the script using php from the crontab

# crontab -e
00 * * * * /usr/bin/php/var/www/devicecheck.php

Method B: Run the php script using URL from the crontab

If your php script can be invoked using an URL, you can lynx, or curl, or wget to setup your crontab as shown below.

The following script executes the php script (every hour) by calling the URL using the lynx text browser. Lynx text browser by default opens a URL in the interactive mode. However, as shown below, the -dump option in lynx command, dumps the output of the URL to the standard output.

00 * * * * lynx -dump http://www.yourwebsite.com/yourscript.php

The following script executes the php script (every 5 minutes) by calling the URL using CURL. Curl by default displays the output in the standard output. Using the “curl -o” option, you can also dump the output of your script to a temporary file as shown below.

*/5 * * * * /usr/bin/curl -o temp.txt http://www.yourwebsite.com/yourscript.php

The following script executes the php script (every 10 minutes) by calling the URL using WGET. The -q option indicates quite mode. The “-O temp.txt” indicates that the output will be send to the temporary file.

*/10 * * * * /usr/bin/wget -q -O temp.txt http://www.yourwebsite.com/yourscript.php

UPDATE::

# chmod a+x /home/username/yourscript.php
# crontab -e
00 * * * * /home/username/yourscript.php

In PHP, how to detect the execution is from CLI mode or through browser ?

Use the php_sapi_name() function.

if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}

Here are some relevant notes from the docs:

php_sapi_name — Returns the type of interface between web server and PHP

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.



Related Topics



Leave a reply



Submit