How can PHP automatically follow 301/302 redirects when reading website content via HTTP?
When reading website content via HTTP in PHP, you can use the cURL library to automatically follow 301/302 redirects. By setting the `CURLOPT_FOLLOWLOCATION` option to `true`, cURL will handle the redirects internally, so you don't have to manually handle them in your code.
$url = 'http://example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if($response === false){
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
echo $response;