Reputation: 35265
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.
Upvotes: 54
Views: 58564
Reputation: 1849
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
Upvotes: 1
Reputation: 359
@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.
Upvotes: 3
Reputation: 45
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);
Upvotes: -2
Reputation: 2647
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.
Upvotes: 8
Reputation: 33904
the @
suppresses error messages.
you cloud use:
$file = 'script.php';
if(file_exists($file))
include($file);
Upvotes: 0
Reputation:
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
Upvotes: 1
Reputation: 3914
if(file_exists('file.php'))
include 'file.php';
That should do what you want
Upvotes: 103