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?
The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
The require() function will stop the execution of the script when an error occurs. The include() function does not give a fatal error. The include() function is mostly used when the file is not required and the application should continue to execute its process when the file is not found.
They are all ways of including files. Require means it needs it. Require_once means it will need it but only requires it once. Include means it will include a file but it doesn't need it to continue.
The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
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 @
.
Check out the stream_resolve_include_path function, it searches with the same rules as include().
http://php.net/manual/en/function.stream-resolve-include-path.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With