Home  >  Article  >  Backend Development  >  How Can I Efficiently Get HTTP Status Codes Using PHP\'s Curl?

How Can I Efficiently Get HTTP Status Codes Using PHP\'s Curl?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 16:37:02195browse

How Can I Efficiently Get HTTP Status Codes Using PHP's Curl?

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:

  • Validate the URL: Ensure the URL is valid before making the request to save time.
  • Request Headers Only: Specify that only headers are retrieved, excluding body content. This significantly reduces data transfer time:
<code class="php">curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);</code>
  • Refer to Additional Documentation: For further guidance on obtaining HTTP status codes, refer to the documentation on checking URL existence:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn