php 如何仅在文件存在时包含
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4604965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include only if file exists
提问by Emanuil Rusev
I need an include
function / statement that will include a file only if it exists. Is there one in PHP?
我需要一个include
函数/语句,它仅在文件存在时才包含文件。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.
您可能建议使用,@include
但该方法存在问题 - 如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP 将不会输出警告。
回答by Colum
if(file_exists('file.php'))
include 'file.php';
That should do what you want
那应该做你想做的
回答by oezi
回答by Nickkk
Based on @Select0r's answer, I ended up using
根据@Select0r 的回答,我最终使用了
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.
即使您将此代码写入已包含在另一个目录中的文件中的文件中,此解决方案也有效。
回答by Select0r
How about using file_exists
before the include
?
file_exists
之前使用怎么样include
?
回答by Stephane JAIS
Check out the stream_resolve_include_path
function.
回答by Stephane JAIS
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
我认为你必须使用file_exists
,因为如果有这样的包含,它会在这里列出:http: //php.net/manual/en/function.include.php
回答by valiD
@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.
在前面使用 at 会忽略该函数可能产生的任何错误。不要滥用它,因为它比检查 if 慢得多,但它是最短的代码替代方案。
回答by Floern
the @
suppresses error messages.
在@
抑制错误消息。
you cloud use:
你云使用:
$file = 'script.php';
if(file_exists($file))
include($file);
回答by Abdul Gaffar Shah
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);
回答by Liang Lee
<?php
if(file_exists('file.php'))
include 'file.php';
}else{
header("Location: http://localhost/);
exit;
}