我需要一个include
函数/语句,只有在文件存在时才会包含该文件。 PHP中是否有一个?如何只包含文件存在
您可能会建议使用@include
,但这种方法存在问题 - 如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP将不会输出警告。
我需要一个include
函数/语句,只有在文件存在时才会包含该文件。 PHP中是否有一个?如何只包含文件存在
您可能会建议使用@include
,但这种方法存在问题 - 如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP将不会输出警告。
如何在include
之前使用file_exists
?
尝试使用file_exists()
if(file_exists($file)){
include $file;
}
我认为你必须使用file_exists
,因为如果有这样的包括,它会被列在这里: http://php.net/manual/en/function.include.php
@
禁止显示错误消息。
你使用云:
$file = 'script.php';
if(file_exists($file))
include($file);
<?php
if(file_exists('file.php'))
include 'file.php';
}else{
header("Location: http://localhost/);
exit;
}
解释!说明!说明! – 2017-10-26 19:55:17
这看起来像特定的业务需求。此外,如果你在你的index.php文件中这样做,它将是无止境的循环。 – Roland 2018-01-17 15:51:47
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);
基于@ Select0r的答案,我结束了使用
if (file_exists(stream_resolve_include_path($file)))
include($file);
此解决方案,即使你在已列入自己从别的目录下的文件的文件编写代码。
@include($file);
在前面使用,忽略该函数可能产生的任何错误。 不要滥用这个,因为它比用if检查更省事,但它是最短的代码替代方案。
你是否要求一些与这些答案不同的东西给你?我很难相信你知道'@'和'include()'而不是'file_exists()'。 – JakeParis 2011-01-05 14:17:11
@JMC Creative,我知道'file_exists()'方法。我应该提到这一点。 – 2011-01-05 14:31:57