Envoirnment : Linux, PHP
Scenario : I have written a script which will be set as a cron. Now the case is that I want the script to run only through cron and not through any browser (any web browser including mobile browsers). So I am looking for a function something like browserValidate.
The script is written in MVC framework and will be run as
/usr/bin/GET http://xyz.com/abc/pqr
Please help me with this.
Thanks in advance.
The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script.
I am aware of exit but it clearly states: Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.
php” file is placed inside the “htdocs” folder. If you want to run it, open any web browser and enter “localhost/demo. php” and press enter. Your program will run.
You need three things to make this work: the PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server.
As @Mob said, the sure fire way to achieve this is to put the script in a place where it cannot be accessed through the web server. If this is not possible or you don't want to do it for some reason, you need to detect whether the script was called via a web server or through the command line.
My favourite approach for this (there are many) is:
$isRunningFromBrowser = !isset($GLOBALS['argv']);
This means that if $isRunningFromBrowser
is true, you just exit/return an error message/whatever.
When executing the script from within crontab, you could use the $_SERVER
superglobal to either check for Apache generated entries (HTTP_*
) or - since $_SERVER
reflects the executing binary's environment - define a certain environment variable prior to execution:
# in the crontab
FOOVAR=1 /usr/bin/php5 script.php
Then, in script.php, check for FOOVAR
existence:
if (!isset($_SERVER['FOOVAR']))
die('No browser access.');
If your cronjob is being executed with wget
and the client IP is the server's, you could add this to an .htaccess
file:
SetEnvIf Remote_Addr "192.168.0.1" FOOVAR=1
This will set FOOVAR
only if the client's IP address is "192.168.0.1".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With