PHP: Returning a variable from an include file.
This is a quick tutorial on how to “return” variables from an included PHP file. This design can be used whenever you want to assign the return value of an included file to a variable in your main script (the main script in this case is the script that “called” your included file). In this example, I will be using two files: main.php and included_file.php
Take a look at the following code snippet:
included_file.php
This is the file that we will be including:
Note that in the example above, I am returning a string variable. To return a variable from an included file, you MUST use the return statement.
main.php
This is our main script. This is the file that “calls” our included file:
Above, we include the file included_file.php and assign its return value to a variable called $stringVariable.
If you run the code above, you’ll see that the include statement returned the string variable that we created in included_file.php
In the past, I have seen type of design being used to store and retrieve configuration values. For example: In the MVC framework Laravel, there is a config folder that contains files such as mail.php, session.php and database.php. If you open any of these files, you’ll see that each file is returning an associative array that contains configuration values.
Here is a basic example of an include file returning configuration values:
'localhost', 'db_user' => 'root', 'db_pass' => '', 'db_name' => 'test' );
Then, if we want to retrieve the configuration values above:
If you run the code above, you will see that $databaseConfig contains the associative array that we created in database.php
get_included_files
Gets the names of all files that have been included using include , include_once , require or require_once .
Parameters
This function has no parameters.
Return Values
Returns an array of the names of all files.
The script originally called is considered an «included file,» so it will be listed together with the files referenced by include and family.
Files that are included or required multiple times only show up once in the returned array.
Examples
Example #1 get_included_files() example
include ‘test1.php’ ;
include_once ‘test2.php’ ;
require ‘test3.php’ ;
require_once ‘test4.php’ ;
foreach ( $included_files as $filename ) echo » $filename \n» ;
>
The above example will output:
/path/to/abc.php /path/to/test1.php /path/to/test2.php /path/to/test3.php /path/to/test4.php
See Also
- include — include
- include_once — include_once
- require — require
- require_once — require_once
- get_required_files() — Alias of get_included_files
User Contributed Notes 7 notes
As of PHP5, this function seems to return an array with the first index being the script all subsequent scripts are included to.
If index.php includes b.php and c.php and calls get_included_files(), the returned array looks as follows:
If you want to know which is the script that is including current script you can use $_SERVER[‘SCRIPT_FILENAME’] or any other similar server global.
If you also want to ensure current script is being included and not run independently you should evaluate following expression:
If this expression returns TRUE, current script is being included or required.
If you have a MAIN php script which you don’t want to be included by other scripts, you could use this function. For example:
main.php:
function blockit ()
$buf = get_included_files ();
return $buf [ 0 ] != __FILE__ ;
>
blockit () and exit( «You can not include a MAIN file as a part of your script.» );
print «OK» ;
?>
So other script couldn’t include main.php to modify its internal global vars.
It’s perhaps not clear from the existing docs that the returned list contains nested include files as well.
That is, if A.php includes B.php, and B.php includes C.php, the result returned when calling get_included_files() from inside A.php WILL contain ‘C.php’.
As is often the case, YMMV. I tried the __FILE__ and SCRIPT_FILENAME comparison and found this:
SCRIPT_FILENAME: /var/www/cgi-bin/php441
__FILE__: /raid/home/natpresch/natpresch/RAY_included.php
Gives one when the script is standalone and always more than one when the script is included.
This function aims to perform filtering of files that have been included :
function setIncludeFiles ( $arrayInc = array()) <
$incFiles = get_included_files ();
if(( count ( $arrayInc )> 0 )&&( count ( $incFiles )> 0 )) <
$aInt = array_intersect ( $arrayInc , $incFiles );
if( count ( $aInt )> 0 ) <
return false ;
>elseif( count ( $aInt ) < 1 ) <
foreach( $arrayInc as $inc ) <
if( is_file ( $inc ))
include( $inc );
else <
return false ;
>
>
>
>else <
return false ;
>
>
?>
Usage :
$toBeInclude = array( ‘/data/your_include_files_1.php’ ,
‘/data/your_include_files_2.php’ ,
‘/data/your_include_files_3.php’ ,
);
setIncludeFiles ( $toBeInclude );
?>
Return false if something goes wrong.
This is a great way to emulate Python’s ‘__name__ = «__main__»‘
if( get_included_files ()[ 0 ] === __FILE__ ) doStuff ();
?>
Something that’s not noted in the docs, if a file is included remotely and you do a get_included_files() in the include itself it will *not* return the document that included it.
?>
test3.php (server 192.168.1.11):
Array ( [0] => /var/www/localhost/htdocs/test/test3.php )
Which means you can use get_included_files() to help intercept and prevent XSS-style attacks against your code.
- PHP Options/Info Functions
- assert_options
- assert
- cli_get_process_title
- cli_set_process_title
- dl
- extension_loaded
- gc_collect_cycles
- gc_disable
- gc_enable
- gc_enabled
- gc_mem_caches
- gc_status
- get_cfg_var
- get_current_user
- get_defined_constants
- get_extension_funcs
- get_include_path
- get_included_files
- get_loaded_extensions
- get_required_files
- get_resources
- getenv
- getlastmod
- getmygid
- getmyinode
- getmypid
- getmyuid
- getopt
- getrusage
- ini_alter
- ini_get_all
- ini_get
- ini_parse_quantity
- ini_restore
- ini_set
- memory_get_peak_usage
- memory_get_usage
- memory_reset_peak_usage
- php_ini_loaded_file
- php_ini_scanned_files
- php_sapi_name
- php_uname
- phpcredits
- phpinfo
- phpversion
- putenv
- set_include_path
- set_time_limit
- sys_get_temp_dir
- version_compare
- zend_thread_id
- zend_version
- get_magic_quotes_gpc
- get_magic_quotes_runtime
- restore_include_path
Return from include file
in PHP, how would one return from an included script back to the script where it had been included from? IE: 1 — main script 2 — application 3 — included Basically, I want to get back from 3 to 2, return() doesn’t work. Code in 2 — application
$page = "User Manager"; if($permission["13"] !=='1') < include("/home/radonsys/public_html/global/error/permerror.php"); return(); >
Make sure you are calling return() at the top-level scope in the included script (i.e. not in a function)
What happens when you invoke return from your #3/included script? Can you post a sample of your code?
5 Answers 5
also gives the same result
This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files.
See the PHP manual, especially Example #5 include and the return statement and its description.
It should be noted that in most cases this would be considered to be a somewhat bad coding style, as it treats the include file as a function. A more ‘standard’ approach would be to put functions with a proper name in the include file, include the file (without any return statement outside of functions) and then call the needed function.
Take care when using parenthesis (i.e., include(«x.php»); rather than include «x.php»), when it comes to return values. See Example 4 in the PHP documentation for include : php.net/manual/en/function.include.php
@Pacerier, as said, because it treats the include file as a function, thus relying on a rather unusual, language specific and not very explicit behavior. Things like that can easily be missed by the fellow developer diving in for maintenance (or cost some time to understand what’s going on), so if there is an equivalent, more common approach (like using explicit function calls in this case), it should be preferred.
@HenrikOpel That sounds like «Don’t use all the features of PHP, because other people don’t.» Doesn’t that set up a bad precedent for effectively removing features from a language, eventually boiling it down to the least common developer?