Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 447
MintDeparture Avatar asked Feb 12 '10 14:02

MintDeparture


People also ask

How we use include() and require() function in PHP?

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.

What is the difference between an include and a require in PHP?

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.

What is difference between include () require () and require_once ()?

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.

How to use require_ once in PHP?

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.


2 Answers

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 @.

like image 94
Johannes Gorset Avatar answered Sep 19 '22 15:09

Johannes Gorset


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

like image 40
Stephane JAIS Avatar answered Sep 18 '22 15:09

Stephane JAIS