I am trying to access a JSON file through Curl but it always shows a 403 forbidden error.
I am using Cloudflare on my site.
Here is the code, only else block is running.
I can access this JSON through browser and FTP
there is no error but through Curl and wget
it shows 403
.
$url = "https://example.com/pub/media/sample.json";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: curl/7.39.0');
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 200) {
$status = true;
} else {
$status = false;
}
curl_close($ch);
if ($status){
echo 'sucess';
}
else{
echo $code.' My File Error '. $url;
}
2
Answers
This fixed my issue.
I was using
Curl
on my server to access files but it was not allowingCurl
orWGET
to access any file and Cloudflare was blocking all requests.I went to Cloudflare and whitelisted the my server own IP in
If you’re using cURL to access a JSON file and getting a 403 Forbidden error, it could be because the server is preventing requests from cURL. Here are some points for you to look into and try.
User-Agent Header : Verify the correct setting for the User-Agent header. Requests that contain a suspicious User-Agent header or don’t provide one are sometimes blocked by servers, including Cloudflare. Take off the "User-Agent:" prefix from the CURLOPT_USERAGENT option in your code:
curl_setopt($ch, CURLOPT_USERAGENT, ‘curl/7.39.0’);
Cookies and headers : Certain websites might not allow access without certain cookies or headers. Curl can be used to attempt to duplicate browser headers. As an example
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘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’,
‘Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8′,
‘Accept-Language: en-US,en;q=0.9’,
));
Note: Depending on what your browser sends, modify the headers.
Verify the Cloudflare Security Preferences, Cloudflare Rate Limitation, and Access Restrictions.
follow this link : https://copyprogramming.com/howto/curl-gives-403-error