0

I am trying to list files from google drive folder.

If I use jquery I can successfully get my results:

var url = "https://www.googleapis.com/drive/v3/files?q='" + FOLDER_ID + "'+in+parents&key=" + API_KEY;

$.ajax({
    url: url,
    dataType: "jsonp"
}).done(function(response) {
     //I get my results successfully
});

However I would like to get this results with php, but when I run this:

$url = 'https://www.googleapis.com/drive/v3/files?q='.$FOLDER_ID.'+in+parents&key='.$API_KEY;
$content = file_get_contents($url);
$response = json_decode($content, true);
echo json_encode($response);
exit;

I get an error:

file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden

If I run this in browser:

https://www.googleapis.com/drive/v3/files?q={FOLDER_ID}+in+parents&key={API_KEY}

I get:

The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.

I have set up referrers for my website and localhost in google developers console.

Can someone explain me what is the difference between jquery and php call and why does php call fails?

Simon H
  • 2,495
  • 4
  • 30
  • 38
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • Possible duplicate of [Why I'm getting 500 error when using file\_get\_contents(), but works in a browser?](https://stackoverflow.com/questions/10524748/why-im-getting-500-error-when-using-file-get-contents-but-works-in-a-browser) – TheNavigat Jul 24 '17 at 15:14

1 Answers1

0

It's either the headers or the cookies.

When you conduct the request using jQuery, the user agent, IP and extra headers of the user are sent to Google, as well as the user's cookies (which allow the user to stay logged in). When you do it using PHP this data is missing because you, the server, becomes the one who sends the data, not the user, nor the user's browser.

It might be that Google blocks requests with invalid user-agents as a first line of defense, or that you need to be logged in.

Try conducting the same jQuery AJAX request while you're logged out. If it didn't work, you know your problem.

Otherwise, you need to alter the headers. Take a look at this: PHP file_get_contents() and setting request headers. Of course, you'll need to do some trial-and-error to figure out which missing header allows the request to go through.

Regarding the referrer, jQuery works because the referrer header is set as the page you're currently on. When you go to the page directly there's no referrer header. PHP requests made using file_get_contents have no referrer because it doesn't make much sense for them to have any.

TheNavigat
  • 864
  • 10
  • 30