How to include a file only if the file exists in PHP?
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 c开发者_如何学JAVAase the file to be included exists, PHP will not output warnings if the parser find something wrong in the included file.
if(file_exists('file.php'))
include 'file.php';
That should do what you want
Try using file_exists()
if(file_exists($file)){
include $file;
}
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.
How about using file_exists
before the include
?
Check out the stream_resolve_include_path
function.
@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.
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
the @
suppresses error messages.
you cloud use:
$file = 'script.php';
if(file_exists($file))
include($file);
I'm posting these as an answer since they were discussed in comments:
if(is_file($file)) {
include $file;
}
Or:
is_file($file) AND include $file;
This is theoretically faster and also safer than using file_exists
because it skips right to using the simple test is_file
without having to check whether it's a file vs folder, etc, and it also will never load a folder (potentially unsafe).
Here's a brief example:
<?php
$file = "test.txt";
if(is_file($file)) {
echo ("$file is a regular file");
} else {
echo ("$file is not a regular file");
}
?>
Ref: https://www.w3schools.com/php/func_filesystem_is_file.asp
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);
<?php
if(file_exists('file.php'))
include 'file.php';
}else{
header("Location: http://localhost/);
exit;
}
精彩评论