How to Efficiently Obtain HTTP Code with PHP Using curl
When using curl to determine the status of a website, such as whether it's up, down, or redirecting, it's important to minimize performance overhead. However, the provided code downloads the entire page, adversely affecting performance.
To optimize this process, consider the following steps:
<code class="php">curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true);</code>
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)) { return false; }
Optimized Code:
<code class="php">$url = 'http://www.example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo 'HTTP code: ' . $httpcode;</code>
The above is the detailed content of How Can I Efficiently Get HTTP Status Codes Using PHP\'s Curl?. For more information, please follow other related articles on the PHP Chinese website!