代码之家  ›  专栏  ›  技术社区  ›  Axel

检查字符串是否可以是PHP中的路径

  •  4
  • Axel  · 技术社区  · 6 年前

    当我使用 file_get_contents , is_file , realpath , file_exists 对于不是路径的字符串,我得到以下警告。


    你到底想干什么?你可以问。。。

    我想创建一个这样的函数。

    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\u或\u内容 将是文件本身的内容(例如动态创建的图像的二进制数据,该图像甚至没有路径(至少还没有路径))。在后一种情况下,我上面提到的所有与字符串相关的函数(例如 file_exists() )将抛出一个警告(参见上面的引用)。



    realpath('xyz') 不会发出警告但是
    realpath( file_get_contents('path/to/actual/image.jpg') ) 做。。。

    所以呢 上面提到的其他函数区分 一串 或者 有效路径的字符串 . 那我们怎么能事先做到呢?

    3 回复  |  直到 4 年前
        1
  •  4
  •   Barmar 0___________    5 年前

    这可能是使用 @

    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() 将返回一个假值 不会让它抱怨坏弦。

    在Linux上,路径中唯一不允许的字符是空字节。所以你可以检查一下:

    if (strpos($path_or_contents, "\0") === false) {
        return file_get_contents($path_or_contents);
    } else {
        return $path_or_contents;
    }
    
        2
  •  5
  •   Daan    6 年前

    我相信这正是你想要的。 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
    }
    
        3
  •  0
  •   Madhur Bhaiya    6 年前

    我想你错过了 file_exists 功能。根据文件:

    文件\u exists检查文件或目录是否存在

    bool file_exists ( string $filename )
    

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

        4
  •  0
  •   The Godfather    5 年前

    file_exists return strpos($path, "\0") === false

    不过,通常您也不希望在文件名中包含不可打印的字符,因此仅使用 ctype_print 将路径传递给 文件\u存在 (正如达安所建议的)。

    即使每个人都使用 要检查。。。如果该文件存在,则此函数(以及其他一些函数)的作用不止于此。

    null \0 ). 这是一个PHP bug

    这是非常令人困惑的行为。尽管 documentation 他说 文件\u存在

    据PHP社区的一位人士说: