检查字符串是否可以是路径(无警告)

时间:2018-09-19 19:21:56

标签: php validation path suppress-warnings

如何在不警告字符串不是有效路径的情况下检查字符串在PHP中是否为有效路径?

当我将file_get_contentsis_filerealpathfile_exists与不是路径的字符串一起使用时,会收到以下警告。

  

“ function_name()”期望参数1为有效路径,[...]中给出的字符串

那么如何确定字符串是否可以是有效路径。


您想做什么?您可能会问...

好吧,我想创建一个像这样的函数。

funtion my_smart_function( string $path_or_content )
{
    $content = is_file_without_warning_if_not_a_valid_path( $path_or_content )
             ? file_get_contents( $path_or_content )
             :                    $path_or_content;
    // do nice stuff with my $content
}

有时$path_or_content是文件的有效路径,有时$path_or_content本身就是文件的内容(例如,动态创建的图像的二进制数据甚至没有有一个路径(至少还没有)。在后一种情况下,我上面提到的所有这些与字符串相关的函数(例如file_exists())都将发出警告(请参见上面的引用)。


我想知道的事情。
realpath('xyz')不会发出警告,但
realpath( file_get_contents('path/to/actual/image.jpg') )确实...

因此realpath和上面提到的其他函数区分字符串或有效路径的字符串那我们该怎么做?

4 个答案:

答案 0 :(得分:4)

这可能是使用@修饰符来抑制错误的合理时间。

funtion my_smart_function( string $path_or_content )
{
    $content =      @file_exists( $path_or_content )
             ? file_get_contents( $path_or_content )
             :                    $path_or_content;
}

如果该路径无效,则file_exists()将返回false,而@将使其免受抱怨错误的字符串的影响。

在Linux上,路径中唯一不允许的字符是空字节。因此,您只需检查一下即可:

if (strpos($path_or_contents, "\0") === false) {
    return file_get_contents($path_or_contents);
} else {
    return $path_or_contents;
}

答案 1 :(得分:3)

我相信这正是您想要的。 ctype_print检查提供的字符串中的所有字符是否可打印。如果是这样,请将其传递给file_exists

function my_smart_function( $path_or_content )
{

    $content = ctype_print($path_or_content) && file_exists( $path_or_content )
             ? file_get_contents( $path_or_content )
             :                    $path_or_content;

    // do nice stuff with my $content
}

答案 2 :(得分:1)

我认为您错过了file_exists功能。来自文档:

  

file_exists —检查文件或目录是否存在

bool file_exists ( string $filename )
  

如果文件名指定的文件或目录存在,则返回TRUE;否则,返回TRUE。   否则为假。

答案 3 :(得分:1)

file_exists不会检查路径是否为有效路径并具有未记录的行为。同时,没有检查路径是否有效的功能。最低限度的检查可能是Barmar建议的:return strpos($path, "\0") === false

但是,通常您都不希望文件名中无法打印的字符,因此,在将路径传递到ctype_print之前仅使用file_exists函数是合理的假设(如Daan所建议)。

背景知识

即使每个人都使用file_exists来检查...该文件是否存在,但此功能(和其他一些功能)的作用远不止于此。

确切地说,如果path不是有效路径(即包含null),它将返回\0。这是PHP bug

这是非常令人困惑的行为。即使documentationfile_exists“如果存在由filename指定的文件或目录,则返回TRUE;否则,返回FALSE。”,这不是当前的实现行为。

根据来自PHP社区的某人:

  

否,file_exists不测试有效路径。它测试“文件”是否存在。假定您提供的路径是有效的,因为如果没有,那么它就不可能存在。