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. */
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!