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

检查远程服务器上是否存在文件(使用PHP)[关闭]

php
  •  -2
  • Malte  · 技术社区  · 1 年前

    我知道这里和网上有很多非常相似的问题,但令我惊讶的是,我尝试过的所有建议答案(至少十五个)在我的情况下都不起作用。基本上,我想通过PHP检查德国数学奥林匹克网站服务器上是否存在某些文件。我使用两个文件和相关路径进行测试:URL

    https://mathematik-olympiaden.de/moev/index.php?option=com_download&thema=a&format=raw&datei=A40051.pdf

    不起作用。但是,如果倒数第二位数字从“5”更改为“6”,则URL

    https://mathematik-olympiaden.de/moev/index.php?option=com_download&thema=a&format=raw&datei=A40061.pdf

    确实有效。但我在这里和其他地方发现的所有建议解决方案都未能检测到第一个URL有错误,我也不知道为什么。我根据其他地方的建议进行的一次尝试是:

    <?php
    
    function FileExists($url) {
      stream_context_set_default(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
      );
      $headers = get_headers($url, 1);
      $file_found = stristr($headers[0], '200');
      return $file_found;
    }
    
    $url1 = "https://mathematik-olympiaden.de/moev/index.php?option=com_download&thema=a&format=raw&datei=A40051.pdf";
    
    $url2 = "https://mathematik-olympiaden.de/moev/index.php?option=com_download&thema=a&format=raw&datei=A40061.pdf";
    
    echo FileExists($url1);
    echo FileExists($url2);
    ?>
    

    但是,在这两种情况下,代码都会返回“OK”。

    有人能给我一个PHP函数来检测第一个URL是否正确吗?

    非常感谢。

    1 回复  |  直到 1 年前
        1
  •  0
  •   hakre    1 年前

    您正在检查状态代码。虽然使用HTTP通常是正确的,但请注意您请求的是PHP脚本。

    PHP脚本 无论查询参数如何,都存在。

    真不敢想象你试了15次 不同的 答案在网站上,但对于代码示例:

    1. 检查预期行上的200状态代码
    2. 检查内容长度
        ...
    
        $headers = get_headers($url, true);
        stream_context_set_default($previous);
    
        [$status] = sscanf($headers[0] ?? '', 'HTTP/1.1 %d OK');
    
        return $status === 200 && isset($headers['Content-Length']);
    }
    

    由于您还发现不同网站的标准/含义可能存在很大差异,我建议您为其提供一个回调函数,您可以在其中采用:

    
    function FileExists($url, ?closure $filter): bool
    {
        $previous = stream_context_get_options(stream_context_get_default());
        stream_context_set_default(['http' => ['method' => 'HEAD', 'follow_location' => 0]]);
        $headers = get_headers($url, true);
        stream_context_set_default($previous);
    
        [$status] = sscanf($headers[0] ?? '', 'HTTP/1.1 %d OK');
    
        return $status === 200 && $filter ? $filter($headers) : true;
    }
    
    $url1 = "https://example.net/path/to/script.php?option=a";
    $url2 = "https://example.net/path/to/script.php?option=b";
    
    var_dump(
        FileExists($url1, fn (array $headers): bool => isset($headers['Content-Length'])),
        FileExists($url2, fn (array $headers): bool => isset($headers['Content-Length'])),
    ); // bool(false), bool(true)
    

    使用你偶然发现的零件,使它们能够注射(=灵活)。

    推荐文章