使用cURL获取有效的网址及其状态

时间:2015-12-19 11:24:15

标签: php curl cron

我写了一个PHP脚本,它将循环通过约。 500个网址并检查其状态:

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_exec($ch);

$destURL = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

echo $destURL . " - " . $statusCode;

是否可以进一步优化OR还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

你可以用GuzzleHttp轻松地做到这一点:

use GuzzleHttp\TransferStats;

$effectiveURL = '';
$statusCode   = 0;

$client = new GuzzleHttp\Client();
$client->get($url, [
    'on_stats' => function (TransferStats $stats) use (&$effectiveURL, &$statusCode) {

        $effectiveURL = (string) $stats->getEffectiveUri();
        if ($stats->hasResponse()) {
            $statusCode = $stats->getResponse()->getStatusCode();
        }

    },
]);

echo $effectiveURL . '<br>';
echo $statusCode;