【问题标题】:What is the most efficient way to text URLs for 404 errors为 404 错误发送文本 URL 的最有效方法是什么
【发布时间】:2015-02-06 09:11:02
【问题描述】:

我有兴趣了解什么是测试服务器响应代码(例如 404)的 URL 的最佳/最精简方法。 我目前正在使用与 get_headers 的 php 手册的 cmets 中可以找到的非常相似的东西:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}

if(intval(get_http_response_code('filename.jpg')) < 400){
// File exists, huzzah!
}
?>

但是,在 foreach 例程中使用这个扩展超过 50 多个 URL 通常会导致我的服务器放弃并报告 500 响应(请原谅对确切错误的含糊不清)。那么,不知道有没有一种资源占用少,并且可以批量查看URL响应码的方法呢?

【问题讨论】:

  • 您的服务器是否启用了 curl-extension?
  • 我很惭愧地承认它是上帝,并且迄今为止避免了 curl 扩展(通过假设)......

标签: php url http-status-code-404 get-headers server-response


【解决方案1】:

您可以使用curl_multi_* 函数同时执行多个 curl 请求。

但是,这仍然会阻止执行,直到最慢的请求返回(以及一些额外的响应解析时间)。

这样的任务应该使用 cronjobs 或类似的替代方案在后台执行。

此外,github 和 co. 上有多个库,它们包装了 curl 扩展以提供更好的 api。

概念解析为:(cpu "fix" by Ren@php-docs)

function getStatusCodes(array $urls, $useHead = true) {
    $handles = [];
    foreach($urls as $url) {
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_NOBODY => $useHead,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER => 0
        ];
        $handles[$url] = curl_init();
        curl_setopt_array($handles[$url], $options);
    }

    $mh = curl_multi_init();

    foreach($handles as $handle) {
        curl_multi_add_handle($mh, $handle);
    }

    $running = null;
    do {
        curl_multi_exec($mh, $running);
        curl_multi_select($mh);
    } while ($running > 0);

    $return = [];
    foreach($handles as $handle) {
        $return[$eUrl = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL)] = [
            'url' => $eUrl,
            'status' => curl_getinfo($handle, CURLINFO_HTTP_CODE) 
        ];
        curl_multi_remove_handle($mh, $handle);
        curl_close($handle);
    }
    curl_multi_close($mh);

    return $return; 
}

var_dump(getStatusCodes(['http://google.de', 'http://stackoverflow.com', 'http://google.de/noone/here']));

【讨论】:

    猜你喜欢
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    相关资源
    最近更新 更多