Detecting URL 404 Errors in PHP
In web scraping, encountering URLs that return 404 (page not found) errors can halt the execution of subsequent code. Hence, it is crucial to implement a mechanism for testing URLs and handling these errors efficiently.
Using curl_getinfo for Error Code Check
One reliable method to determine if a URL returns a 404 error is through PHP's curl extension. The curl_getinfo() function provides access to various HTTP response information, including the error code. Here's how to implement this approach:
$handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); /* Fetch URL contents */ $response = curl_exec($handle); /* Determine HTTP response code */ $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); if ($httpCode == 404) { /* Handle 404 error here */ } curl_close($handle); /* Process $response if no error */
In this code:
Note:
The above is the detailed content of How Can I Efficiently Detect 404 Errors from URLs in PHP?. For more information, please follow other related articles on the PHP Chinese website!