2011-01-05 33 views
35

我需要一個include函數/語句,只有在文件存在時纔會包含該文件。 PHP中是否有一個?如何只包含文件存在

您可能會建議使用@include,但這種方法存在問題 - 如果要包含的文件存在,如果解析器在包含的文件中發現錯誤,PHP將不會輸出警告。

+1

你是否要求一些與這些答案不同的東西給你?我很難相信你知道'@'和'include()'而不是'file_exists()'。 – JakeParis 2011-01-05 14:17:11

+0

@JMC Creative,我知道'file_exists()'方法。我應該提到這一點。 – 2011-01-05 14:31:57

回答

74
if(file_exists('file.php')) 
    include 'file.php'; 

這應該做你想要

+10

或者在一行中沒有條件:'file_exists($ file)AND include $ file;'...... – ircmaxell 2011-01-05 14:18:16

+14

更好地使用'is_file',避免使用目錄 - 以獲得更安全的代碼。 – 2011-01-05 14:36:04

+0

@hakre我想我通過將它與StephaneJAIS的答案相結合來解決這個問題。 – Riking 2014-10-04 20:39:45

3

如何在include之前使用file_exists

0

@禁止顯示錯誤消息。

你使用雲:

$file = 'script.php'; 
if(file_exists($file)) 
    include($file); 
-3
<?php 
    if(file_exists('file.php')) 
     include 'file.php'; 
    }else{ 
     header("Location: http://localhost/); 
     exit; 

    } 
+0

解釋!說明!說明! – 2017-10-26 19:55:17

+0

這看起來像特定的業務需求。此外,如果你在你的index.php文件中這樣做,它將是無止境的循環。 – Roland 2018-01-17 15:51:47

0
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); 
5

基於@ Select0r的答案,我結束了使用

if (file_exists(stream_resolve_include_path($file))) 
    include($file); 

此解決方案,即使你在已列入自己從別的目錄下的文件的文件編寫代碼。

0
@include($file); 

在前面使用,忽略該函數可能產生的任何錯誤。 不要濫用這個,因爲它比用if檢查更省事,但它是最短的代碼替代方案。