Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Code to stop a script to run from browser

Tags:

browser

php

cron

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.

like image 923
Abhishek Sanghvi Avatar asked Jan 17 '12 12:01

Abhishek Sanghvi


People also ask

How do I stop a PHP script from running?

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.

Which function kills the execution of the script immediately PHP?

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.

How do I run a PHP script from a website?

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.

Does PHP run in browser or server?

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.


2 Answers

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.

like image 52
DaveRandom Avatar answered Oct 17 '22 07:10

DaveRandom


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".

like image 20
Linus Kleen Avatar answered Oct 17 '22 08:10

Linus Kleen