9

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?

2
  • 1
    How does the script get called exactly from the server? Using include()? file_get_contents()? Using a file path or a http URL? Commented Sep 5, 2011 at 19:36
  • @Pekka - in the form of an http URL Commented Sep 5, 2011 at 19:38

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Unless it is called from another script, that is from the browser... I understood it that way.
@Rok if a script on the server is making a http:// call, that script will be the caller, not the browser. At least that's how I understand what the OP was saying in the comment
I meant script a.php is called from http:// and calls another script b.php. Therefore b.php script is being called by another script on the server
Unfortunately it's not suitable for the development on local machine. You'll get 127.0.0.1 either way.
stackoverflow.com/a/7225638/535406 is seems to be a good solution relying only on script names — no additional constants or variables required.
|
6

you can create a variable before including your script

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

and check it inside

Comments

2

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

var_dump(PHP_SAPI);

1 Comment

Yeah, maybe OP wanted it your way. It is hard to tell.
1

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
}

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.