Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何仅在文件存在时包含_Php - Fatal编程技术网

Php 如何仅在文件存在时包含

Php 如何仅在文件存在时包含,php,Php,我需要一个include函数/语句,该函数/语句仅在文件存在时才包含该文件。PHP中有吗 您可能建议使用@include,但这种方法存在一个问题-如果要包含的文件存在,如果解析器在包含的文件中发现错误,PHP将不会输出警告。在include之前使用文件\u exists如何 if(file_exists('file.php')) include 'file.php'; 这应该可以满足您的需要尝试使用 我认为您必须使用文件\u exists,因为如果有这样一个包含,它会在这里列出:该@会

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


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

include
之前使用
文件\u exists
如何

if(file_exists('file.php'))
    include 'file.php';
这应该可以满足您的需要

尝试使用


我认为您必须使用
文件\u exists
,因为如果有这样一个包含,它会在这里列出:

@
会抑制错误消息

您可以使用云:

$file = 'script.php';
if(file_exists($file))
  include($file);
检查函数。

函数获取图像($img\u名称){
$filename=“../uploads/”$img_name;
$file\u exists=file\u exists($filename);
如果($file_exists&&!empty($img_name)){
$src='';
}否则{
$src='';
}
返回$src;
}
echo get_image($image_name);

根据@Select0r的回答,我最终使用了

if (file_exists(stream_resolve_include_path($file)))
    include($file);
即使您在另一个目录中的文件中包含自己的文件中编写此代码,此解决方案也可以工作

@include($file);
在前面使用at将忽略该函数可能生成的任何错误。
不要滥用它,因为它比使用if检查慢得多,但它是最短的代码选择。

您是否要求与这些答案不同的东西?我很难相信你知道
@
include()
但不知道
文件存在()
@JMC Creative,我知道
文件存在()
的方法。我应该提到这一点。或者在单行中没有条件:
file\u存在($file)并包含$file
…最好使用
is_file
,这样可以避免使用目录-为了更安全的代码。@hakre我想我通过将其与StephaneJAIS的答案结合起来解决了这个问题。@ircmaxell您能提供一个链接吗?如果当前工作目录与包含路径不同,则此选项不起作用<代码>文件_存在
与当前工作目录相关,但
包含
不一定检查当前工作目录。说明!解释!解释!这看起来像是特定的业务需求。此外,如果你在index.php文件中这样做,它将是无止境的循环。这是误导
stream\u resolve\u include\u path
表示它在路径中查找文件(或者更具体地说,相对于路径的每个元素)。这与写入
include
的文件不同
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);
if (file_exists(stream_resolve_include_path($file)))
    include($file);
@include($file);