2011-01-05 93 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检查更省事,但它是最短的代码替代方案。