我需要一个include
函数/语句,只有存在时才包含文件。 PHP中有一个吗?
你可能会建议使用@include
,但这种方法存在问题 - 如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP将不会输出警告。
if(file_exists('file.php'))
include 'file.php';
那应该做你想要的
<?php
if(file_exists('file.php'))
include 'file.php';
}else{
header("Location: http://localhost/);
exit;
}
尝试使用file_exists()
if(file_exists($file)){
include $file;
}
基于@ Select0r的答案,我最终使用了
if (file_exists(stream_resolve_include_path($file)))
include($file);
即使您将此代码写入已从另一个目录中的文件中包含的文件中,此解决方案仍然有效。
在file_exists
之前使用include
怎么样?
我认为你必须使用file_exists
,因为如果有这样的包含,它会在这里列出:http://php.net/manual/en/function.include.php
@include($file);
在前面使用at,忽略该函数可能生成的任何错误。不要滥用这个,因为它是使用if检查,但它是最短的代码选择。
@
抑制错误消息。
你用云:
$file = 'script.php';
if(file_exists($file))
include($file);
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);