Check if an include (or require) exists
How do you check if an include / require_once exists before you call it, I tried putting it in an error block, but PHP didn’t like that. I think file_exists() would work with some effort, however that would require the whole file path, and a relative include could not be passed into it easily. Are there any other ways?
@GZipp: To all of you who are suggesting the use of file_exists() : checks whether a file or directory exists. is_file() would be a better fit in this case.
@Alix Axel: To all of you who are addressing me: I was suggesting nothing but that Smickie’s assumption (that a relative path can’t easily be transformed to a full path) was wrong. Others have pointed out that the full path isn’t necessary; hence my comment rather than answer.
@AgentConundrum: is_readable() : «Returns TRUE if the file or directory specified by filename exists and is readable, FALSE otherwise».
6 Answers 6
I believe file_exists does work with relative paths, though you could also try something along these lines.
if(!@include(«script.php»)) throw new Exception(«Failed to include ‘script.php'»);
. needless to say, you may substitute the exception for any error handling method of your choosing. The idea here is that the if -statement verifies whether the file could be included, and any error messages normally outputted by include is supressed by prefixing it with @ .
You don’t need the parentheses around the argument value of include . include is not a function but a language construct like echo .
@Gumbo I consider it good practice to use parantheses for language constructs, much like I do with echo() and print() as well.
It better to use include_once or require_once , this will be helpful while using OOP Concept and avoiding redeclaring of classes again.
Check out the stream_resolve_include_path function, it searches with the same rules as include().
A couple of user contributed notes here: stream_resolve_include_path() seems to cache it’s output. After I renamed a file, I had to restart Apache for stream_resolve_include_path() to not return non-existing file name. This was on Windows. It really behaves like include and will only resolve the filename against the include-path, if the path is relative. It makes not much sense to resolve already absolute pathnames anyway.
You can also check for any variables, functions or classes defined in the include file and see if the include worked.
if (function_exists('function_name')) < /*code*/ >
if (class_exists('class_name')) < /*code*/ >
the problem here is that if the include will not work in the first place — it will throw and error / warning ..
file_exists() works with relative paths, it’ll also check if directories exist. Use is_file() instead:
if (is_file('./path/to/your/file.php')) < require_once('./path/to/your/file.php'); >
file_exists would work with checking if the required file exists when it is relative to the current working directory as it works fine with relative paths. However, if the include file was elsewhere on PATH, you would have to check several paths.
function include_exists ($fileName) < if (realpath($fileName) == $fileName) < return is_file($fileName); >if ( is_file($fileName) ) < return true; >$paths = explode(PS, get_include_path()); foreach ($paths as $path) < $rp = substr($path, -1) == DS ? $path.$fileName : $path.DS.$fileName; if ( is_file($rp) ) < return true; >> return false; >
PS == PATH_SEPARATOR && DS == DIRECTORY_SEPARATOR for those wondering, +1, hoping you would fix it, this works great and without overhead of exception and error handlings
I think the correct way is to do:
if(file_exists(stream_resolve_include_path($filepath)))
This is because the documentation says that stream_resolve_include_path resolves the «filename against the include path according to the same rules as fopen()/include.»
Some people suggested using is_file or is_readable but that´s not for the general use case because in the general use, if the file is blocked or unavailable for some reason after file_exists returns TRUE, that´s something you need to notice with a very ugly error message right on the final user´s face or otherwise you are open to unexpected and inexplicable behavior later with possible loss of data and things like that.
get_included_files
Получает имена всех файлов, которые были включены в скрипт с использованием include , include_once , require или require_once .
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает массив, содержащий имена всех файлов.
Скрипт, который был загружен изначально, рассматривается как «включённый файл», поэтому он также попадёт в список файлов включённых функцией include или другими.
Файлы, добавляемые в скрипт неоднократно, попадут в массив только в одном экземпляре.
Примеры
Пример #1 Пример использования get_included_files()
// Этот скрипт расположен в файле abc.php
?php
include ‘test1.php’ ;
include_once ‘test2.php’ ;
require ‘test3.php’ ;
require_once ‘test4.php’ ;
foreach ( $included_files as $filename ) echo » $filename \n» ;
>
Результат выполнения данного примера:
/path/to/abc.php /path/to/test1.php /path/to/test2.php /path/to/test3.php /path/to/test4.php
Смотрите также
- include — include
- include_once — include_once
- require — require
- require_once — require_once
- get_required_files() — Псевдоним 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/информационные функции
- 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
PHP: List all includes
I have a large complex PHP project made up of many PHP files. Is there some function I can call in my code that will return a list of all included files?
3 Answers 3
get_included_files or get_required_files (alias of get_included_files )
?> ----- The above example will output: abc.php test1.php test2.php test3.php test4.php
You can just use var_dump(get_included_files()) instead of using a foreach loop. The function returns an array.
register_shutdown_function( function() < your_logger(get_included_files()); >);
get_included_files will be called at the end of script execution, so u`ll get full list of included files
While this may be the answer, it is recommended to include documentation and/or explanation in your answer.
This is not true, the function will only return the included files, at the order where the function has been called.
This question is in a collective: a subcommunity defined by tags with relevant content and experts.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.