Who is calling php script browser or cron

a door having a knock knob

Identifying who calls php script

Php script can called from different places or clients. Do you Want to know which client, browser or command line, is calling your php script?
Wanted to handle differently when the script is called from command line
Then use php_sapi_name

Yeah, this sapi thing – Server API is a bit bad boy. You might want to check a manual value comparison before deploying it your server as the sapi return type might be different for different settings say b/n command line script and webserver.

Also having additional check with $_SERVER and $_ENV variables is also a good one for better guarantee. Like some parameters of the $_SERVER would only be set when called from web server like ‘REQUEST_METHOD’

if (!empty($_SERVER['REQUEST_METHOD'])) {
    echo "hey baby web server, calling you from browser X - wssup";
} else {
    echo "umm.. are you cron? manual? who the heck???";
}

Also using the sapi name

$sapi_id = php_sapi_name();
if (stristr($sapi_id, 'cli')) {
    echo "hello command line interface";
}

Since the above would be a bit more conditional it would be advised if used along with existence of like $_SERVER[‘REQEST_METHOD’]

Using the above snippet, you can tell from which the php script is called from and you can say hello to browser or cron.

See how you would solve these known algorithm problems

Finding missing numbers from billion sequential number list file

binary tree problems with solution

Implementing tokenizer and adding tokens to the linked list

Kadane’s algorithm in C – Dynamic Programming

Array reversal in Recurrsion

Check if two strings are anagrams or not

Find the first occurence of number in the sorted array

Find the pairs that makes K Complementary in the given array java solution

Check if there are three numbers a, b, c giving a total T from array A

Changing decimal number to its binary equivalent

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*