如何仅包含文件存在

问题描述 投票:37回答:10

我需要一个include函数/语句,只有存在时才包含文件。 PHP中有一个吗?

你可能会建议使用@include,但这种方法存在问题 - 如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP将不会输出警告。

php
10个回答
81
投票
if(file_exists('file.php'))
    include 'file.php';

那应该做你想要的


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

    }

9
投票

尝试使用file_exists()

if(file_exists($file)){
  include $file;
}

6
投票

基于@ Select0r的答案,我最终使用了

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

即使您将此代码写入已从另一个目录中的文件中包含的文件中,此解决方案仍然有效。


3
投票

file_exists之前使用include怎么样?


3
投票

1
投票

我认为你必须使用file_exists,因为如果有这样的包含,它会在这里列出:http://php.net/manual/en/function.include.php


1
投票
@include($file);

在前面使用at,忽略该函数可能生成的任何错误。不要滥用这个,因为它是使用if检查,但它是最短的代码选择。


0
投票

@抑制错误消息。

你用云:

$file = 'script.php';
if(file_exists($file))
  include($file);

-1
投票
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);
© www.soinside.com 2019 - 2024. All rights reserved.