Home > Backend Development > PHP Tutorial > How Can I Reliably Check for 404 HTTP Status Codes in PHP?

How Can I Reliably Check for 404 HTTP Status Codes in PHP?

Patricia Arquette
Release: 2024-12-05 17:38:14
Original
200 people have browsed it

How Can I Reliably Check for 404 HTTP Status Codes in PHP?

Simple Method for Verifying 404 Status Codes in PHP

To prevent your code from breaking due to 404 errors, a test is crucial at the outset to ascertain whether a URL returns such an error. This article guides you through an effortless approach to perform this validation.

Initial Approaches: Pitfalls and Limitations

You encountered a suggestion involving fsockopen. However, this method may fail when encountering redirects, as in your mentioned URL. Additionally, you considered using a "head request."

Solution: Utilizing cURL

The PHP bindings of cURL offer a reliable solution. Here's how to implement it:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get content from $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    /* Handle 404 here. */
}

curl_close($handle);

/* Handle $response here. */
Copy after login

By utilizing curl_getinfo, you can effortlessly ascertain the error code. If it corresponds to 404, you can take appropriate actions within the specified block. This approach comprehensively resolves your issue, ensuring that your code seamlessly handles 404 errors.

The above is the detailed content of How Can I Reliably Check for 404 HTTP Status Codes in PHP?. 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