How can PHP be used to read HTTP headers and handle 301 redirects that result in a 200 status code?
To read HTTP headers and handle 301 redirects that result in a 200 status code, you can use the PHP cURL extension to make a request to the URL, follow the redirects, and retrieve the final response headers. By checking the response headers for a 301 status code, you can then manually handle the redirect by making a new request to the redirected URL.
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 301) {
$redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
$ch = curl_init($redirectUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
}
$headers = curl_getinfo($ch);
curl_close($ch);
// Handle the response headers and content as needed