How can the error message "HTTP request failed! HTTP/1.0 403 Forbidden" be resolved when using file_get_contents in PHP?
The error message "HTTP request failed! HTTP/1.0 403 Forbidden" typically occurs when the server is denying access to the requested resource. To resolve this issue, you can try setting a user-agent header in the request to mimic a browser, as some servers block requests without a user-agent. Additionally, you may need to check if the server requires specific headers or authentication credentials to access the resource.
$url = 'https://example.com/api/data';
$options = [
'http' => [
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3\r\n"
]
];
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
if ($data === false) {
echo "Failed to fetch data";
} else {
echo $data;
}