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

Linda Hamilton
Release: 2024-10-31 16:37:02
Original
194 people have browsed it

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>
Copy after login
  • 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;
}
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!