简体   繁体   中英

How to execute php in an external file

Why doesn't this work?

// File hosted on `example.com`
// db-con.php
<?php
  define("DB_HOST" , "host");
  define("DB_NAME" , "name");
  define("DB_USER" , "user");
  define("DB_PASS" , "pass");

-

// File hosted on `another-example.com`
// index.php
<?php
  include 'http://example.com/db-con.php';
  echo DB_HOST;

-

// output
Notice: Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\Users\Alex\Dropbox\Shared\Web\htdocs\BASE_TEMPLATE\index.php on line 14

Surely by including the external file, the php is run, and the constants are defined?

You are not including the file as you see it, but instead including the response of the remote web server when that file is requested .

That is, the remote web server sees a request for db-con.php , loads it up, executes the code (defining constants in its own local process) and returns the output to you (which is probably empty, as the code does not echo anything). Therefore the end result is the same as if you had included an empty file.

Update: dug up the reference from the manual:

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

So how to do it?

Well, including code from a remote server is something you shouldn't really think of doing (although there are ways to make it happen, it's a really bad idea). In any case you won't be able to do it without the explicit cooperation of the remote server (otherwise anyone could include anyone else's configuration file and use get_defined_constants to get the passwords). And if you do it, anyone else would be able to follow the same steps and get hold of your passwords. You don't want that to happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM