Reputation: 1037
I created a REST API with wordpress to get some json data and this is the link is return all the data for me : https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go
and from another domain i have another website made with wordpress also i create PHP script to get those data :
function file_contents($path) {
$str = @file_get_contents($path);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
} else {
return $str;
}
}
try {
$json_data = file_contents("https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go");
var_dump($json_data);
} catch (Exception $e) {
// Deal with it.
echo "Error: " , $e->getMessage();
}
and i got this error instead :
Error: Cannot access 'https://alternativeviager.fr/wp-json/get-all-alternativeviager/v1/go' to read contents.
some help please
Thanks
Upvotes: 0
Views: 2114
Reputation: 715
As your other website is also WordPress, you should consider using the wp_remote_get() function that WordPress provides.
However, to answer your question using file_get_contents()
:
It seems your web server at alternativeviager.fr
is blocking requests that do not contain the User-Agent
header.
I've modified your file_contents
function to include the User-Agent below. Feel free to choose a more suitable User-Agent.
function file_contents($path)
{
$opts = [
'http' => [
'header' => 'User-Agent: PHP'
]
];
$context = stream_context_create($opts);
$str = @file_get_contents($path, false, $context);
if ($str === FALSE) {
throw new Exception("Cannot access '$path' to read contents.");
}
return $str;
}
I would also recommend you avoid using @
to suppress errors as this is preventing the underlying 403 response from being reported which would have helped you to debug the original issue.
Upvotes: 2