Bob
Bob

Reputation: 93

How to check if a php script is being called by another script on the server?

I have a script scripty.php

Sometimes this script gets called through the browser.

Other times it gets called by another script on the server.

How can I (securely) check within scripty.php to see whether or not it is being called by the server?

Upvotes: 9

Views: 6264

Answers (5)

AgelessEssence
AgelessEssence

Reputation: 6741

consider a file named test.php, this is the only code contained:

echo str_replace("\\","/",$_SERVER["SCRIPT_FILENAME"]);
echo str_replace("\\","/",__FILE__);

when a user execute* test.php by browser url, this is the output:

"C:/xampp/htdocs/test.php"
"C:/xampp/htdocs/test.php"

otherwise, differ (( in this case another.php was executed by browser url, who include test.php ))

"C:/xampp/htdocs/another.php"
"C:/xampp/htdocs/test.php"

Upvotes: 1

Robert
Robert

Reputation: 69

On any script that will be calling it define a constant like define("IN_SCRIPT") and within scripty.php you can check for the constant to determine if it's inside another script or not.

e.g.

if(defined("IN_SCRIPT")){
// We must be inside a script right now!
}

or

if(!defined("IN_SCRIPT")){
// We are working alone now
}

Upvotes: 1

Pekka
Pekka

Reputation: 449783

in the form of an http URL

The $_SERVER["REMOTE_ADDR"] variable that gives you the IP address of the client who made the request should be 127.0.0.1 when the script is called from the server.

Upvotes: 8

KingCrunch
KingCrunch

Reputation: 132061

Just a guess: You want to know, if the script its called trough a browser, or from CLI

var_dump(PHP_SAPI);

Upvotes: 2

genesis
genesis

Reputation: 50982

you can create a variable before including your script

$by_script = true;
include("new_script.php");

and check it inside

Upvotes: 6

Related Questions