我需要一個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