How to include only if file exists
PhpPhp Problem Overview
I need an include
function / statement that will include a file only if it exists. Is there one in PHP?
You might suggest using @include
but there is an issue with that approach - in case the file to be included exists, PHP will not output warnings if the parser find something wrong in the included file.
Php Solutions
Solution 1 - Php
if(file_exists('file.php'))
include 'file.php';
That should do what you want
Solution 2 - Php
Try using file_exists()
if(file_exists($file)){
include $file;
}
Solution 3 - Php
Based on @Select0r's answer, I ended up using
if (file_exists(stream_resolve_include_path($file)))
include($file);
This solution works even if you write this code in a file that has been included itself from a file in another directory.
Solution 4 - Php
How about using file_exists
before the include
?
Solution 5 - Php
Check out the stream_resolve_include_path
function.
Solution 6 - Php
@include($file);
Using at in front, ignores any error that that function might generate. Do not abuse this as IT IS WAY SLOWER than checking with if, but it is the shortest code alternative.
Solution 7 - Php
I think you have to use file_exists
, because if there was such an include, it would have been listed here: http://php.net/manual/en/function.include.php
Solution 8 - Php
the @
suppresses error messages.
you cloud use:
$file = 'script.php';
if(file_exists($file))
include($file);
Solution 9 - Php
function get_image($img_name) {
$filename = "../uploads/" . $img_name;
$file_exists = file_exists($filename);
if ($file_exists && !empty($img_name)) {
$src = '<img src="' . $filename . '"/>';
} else{
$src = '';
}
return $src;
}
echo get_image($image_name);
Solution 10 - Php
<?php
if(file_exists('file.php'))
include 'file.php';
}else{
header("Location: http://localhost/);
exit;
}