Google Drive HTTP Upload "not found" issue PHP - php

I'm trying to upload a file to google drive using http header and CURL post, and I get a "not found" returned from google error.
I think it's because of the way Im uploading the file via CURL, Because I never Did it.
Here's My Code :
$file = file_get_contents("./ima.jpg");
$length = strlen($file);
test($file,$length);
function test($file,$length){
$url2="https://www.googleapis.com/upload/drive/v2/filesuploadType=media";
$header = array(
"Content-Type: image/jpeg",
"Content-Length:$length ",
"Authorization: Bearer $token",
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url2);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,false);
curl_setopt ($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$file);
$data2 = curl_exec($ch);
echo $data2;
curl_close($ch);
}
The Token is set in a variable token, and it is a valid token because it works with listing files from google drive, Thank you !

uploadType is a parameter to the URL and needs to be separated using ?, which means that in your case the URL should most likely be;
$url2="https://www.googleapis.com/upload/drive/v2/files?uploadType=media";
See here for more detailed documentation.

Related

PHP cURL return blank page

I had been using PHP curl to get the contents of a file, hosted on a different server. The file can easily be opened on a browser like Chrome etc., but with cURL, it always returns a blank page.
The file is hosted on an Nginx server and even miniproxy.php fails to get contents. Instead, it returns 406 not acceptable. I tried using the HTTP spy extension to monitor the request sent and found the following header:
Upgrade-Insecure-Requests:1
I tried sending the same header along With other headers, but in vain. Still, I couldn't rectify my mistake. On the Internet, I found the zalmos proxy which was able to get the contents of the file. The curl code I wrote is attached below.
$url = "http://smumcdnems01.cdnsrv.jio.com/jiotv.live.cdn.jio.com/" . $ch . "/" . $ch . "_" . $q . ".m3u8" . $tok;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"User-Agent: agent",
"lbcookie: 300",
"devicetype: 1",
"os: android",
"appkey: 1111111",
"deviceId: device id",
"uniqueId: unique id",
"ssotoken: any token",
"Upgrade-Insecure-Requests: 1",
"Host: example.com",
"Connection: keep-alive",
"X-Chrome-offline: persist=0 reason=reload",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding: gzip, deflate, sdch",
"Accept-Language: en-GB,en-US;q=0.9,en;q=0.8",
"subscriberId: any id",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
echo $url;
echo $resp;
I believe that any part is missing in my code which is posing a problem. How can this be rectified?
Check your URL. Curl must give you the response. If it's hit the target URL, either the target URL is not responding to anything when sending the request.
You may be trying to access a websocket. Try to simulate with Postman to get more information.

2ba web API post request with php curl

Im using 2ba its API to receive product information which I later on want to store inside my database. I am trying to create a post request for receiving the data I need. This is the request I want to get to working. And this is my code:
postApiData.php
<?php
/**
* Posts API data based on given parameters at index.php.
*/
// Base url for all api calls.
$baseURL = 'https://api.2ba.nl';
// Version number and protocol.
$versionAndProtocol = '/1/json/';
// All parts together.
$url = $baseURL . $versionAndProtocol . $endPoint;
// Init session for CURL.
$ch = curl_init();
// Init headers. Security for acces data.
$headers = array();
$headers[] = "Authorization: Bearer " . $token->access_token;
// Options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
// Execute request.
$data = curl_exec($ch);
// If there is an error. Show whats wrong.
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
echo "<br>";
echo "Error location: postApiData";
exit();
}
// Ends the CURL session, frees all resources that belongs to the curl (ch).
curl_close($ch);
// String to array.
$data = json_decode($data);
?>
index.php
// Specified url endpoint. This comes after the baseUrl.
$endPoint = 'Product/forGLNAndProductcodes';
// Parameters that are required or/and optional for the endPoint its request.
$parameters = [
'gln' => '2220000075756',
'productcodes' => ['84622270']
];
// Get Supplier info
include("postApiData.php");
print_r($data);
exit();
My API key does for sure work since I have done alot of different GET requests already, also im not getting an access denied error.
The error I get with this code is: The requested URL returned error: 500 Internal Server Error
I also receive a "Bad request" 400 error when I remove the curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters)); part
Is there anyone who knows what im doing wrong?
PS: It's not really possible to try this code yourself unless you have a 2ba account with working key's etc.
Okey I fixed it already...
I had to add some extra headers and change the $parameters values like this:
postApiData.php
// Added this above the authorization.
$headers[] = "Connection: close";
$headers[] = "Accept-Encoding: gzip,deflate";
$headers[] = "Content-Type: application/json";
// Removed the http_build_query part.
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
index.php
// Encoded in a json way as asked by 2ba request.
$parameters = json_encode($parameters);

Why is the curl code not executed in PHP script? (WAMP Server)

I am trying to get a token to use the Microsoft Graph API (https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0) via Curl. I have set up a simple Php file with this function:
function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
"client_id" => "***",
"scope" => "https://graph.microsoft.com/.default",
"client_secret" => "***",
"grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));
$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";
return $token;
curl_error($ch);
}
However, what I want to know is why the curl request is not working. Also the echo after the curl codeblock is not being executed, while 'start gettoken' is. PHP_curl is enabled in my WAMP. Why is this?
Are you sure CURL is enabled because that code you have posted is ok and giving echo response before and after curl execution.
you're sending the token request in a JSON-format, and then you're lying to the server saying it's application/x-www-form-urlencoded-encoded when it's actually application/json-encoded! since these 2 formats are completely incompatible, the server fails to parse it, and... ideally it should have responded HTTP 400 bad request (because your request can't be parsed as x-www-form-urlencoded)
anyhow, to actually send it in the application/x-www-form-urlencoded-format, replace json_encode() with http_build_query()
also get rid of the "Content-Length:"-header, it's easy to mess up (aka error-prone) if you're doing it manually (and indeed, you messed it up! there's supposed to be a space between the : and the number, you didn't add the space, but the usual error is supplying the wrong length), but if you don't do it manually, then curl will create the header for you automatically, which is not error-prone.

Does Marketo API block curl on a per account basis?

I am trying to connect to the Marketo.com REST API using curl.
I can't get a response from the identity service. I only get an error message
"[curl] 6: Couldn't resolve host 'MY_CLIENT_ENDPOINT.mktorest.com'
,
but I can print the constructed url and paste it into a browser address bar and this will provide the expected response with the access_token element.
I can use curl in php and in a terminal to access my gmail account so curl is able to access an https service.
I have tried sending the parameters in the curl url as a get request and also by declaring them with curl's -F option as a post request
My application uses dchesterton/marketo-rest-api available on github, but I have also tried a simple php curl request just to get the access token.
private function getToken() {
$url = "$this->client_url/identity/oauth/token?grant_type=client_credentials&client_id=$this->client_id&client_secret=$this->client_secret";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$errors = curl_error($ch);
curl_close($ch);
file_put_contents($this->logDir . 'access_token_response' . date('Y-m-d') . '.txt', $url . "\n" . $response . "\n", FILE_APPEND);
if ($errors) {
file_put_contents($this->logDir . 'access_token_errors' . date('Y-m-d') . '.txt', $errors . "\n", FILE_APPEND);
}
return $response['access_token'];
}
Again, this fails with the same error but produces a perfectly formed url that I can paste into the browser and get a valid response.
I have also tried this using post instead of get as I have for every other test mentioned, and these have been tried on my localhost and on a test server.
Can anyone explain to me why this would fail?
Does Marketo block curl on a per account basis?
I was trying to implement something similar but my code wasn't working. I'm not sure exactly what is failing but I tried your code and it seems to work perfectly after some slight modifications:
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($curl);
$errors = curl_error($curl);
curl_close($curl);
I hope this helps.

PHP Curl with Google Calendar

<?php
if(isset($_GET['token']))
{
$url="http://www.google.com/calendar/feeds/default/allcalendars/full";
$useragent="PHP 5.2";
$header=array( "GET /accounts/AuthSubSessionToken HTTP/1.1",
"Content-Type: application/x-www-form-urlencoded",
"Authorization: AuthSub token=".$_GET['token'],
"User-Agent: PHP/5.2",
"Host: https://www.google.com",
"Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
"Connection: keep-alive"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);
}
?>
The result is page not found. However, I call http://www.google.com/calendar/feeds/default/allcalendars/full from firefox , it's return XML file. So, I think, my code may wrong. But I can't find the error. :(
That is because you are accessing Google Calendar via your personal port. Whenever you access that specific URL, Google checks to see if you are logged in. If not, it sends a 404. If you are, it outputs the calendar based on the settings you provided. That URL does not specify a specific calendar that it's supposed to pull from the site, and it cannot use the cookies stored on the user's computer because it is being fetched from your server, which will not have any cookies for a calendar. When I try to access that page without logging on, I get a 401 Authorization Required error, which I bet is what PHP is getting and you just don't realize it.
You need to go into your Google Calendar settings and find the embedding options to find a URL that is specific to your account so that it will always fetch an XML feed for your calendar.
Read more about the Google 'Calendar Address' here: http://www.google.com/support/calendar/bin/answer.py?answer=34578
View from other applications: http://www.google.com/support/calendar/bin/answer.py?hl=en&answer=37648
I think that you may be overriding the URL with this line in the header:
GET /accounts/AuthSubSessionToken HTTP/1.1
I think that will point CURL to http://www.google.com/accounts/AuthSubSessionToken
What happens when you remove it?
I got it.... I changed like this
<?php
function make_api_call($url, $token)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
function get_session_token($onetimetoken) {
$output = make_api_call("https://www.google.com/accounts/AuthSubSessionToken", $onetimetoken);
if (preg_match("/Token=(.*)/", $output, $matches))
{
$sessiontoken = $matches[1];
} else {
echo "Error authenticating with Google.";
exit;
}
return $sessiontoken;
}
if(isset($_GET['token']))
{
$sessiontoken=get_session_token($_GET['token']);
$accountxml = make_api_call("http://www.google.com/m8/feeds/contacts/yourmail#gmail.com/full", $sessiontoken);
print_r($accountxml);
}
else
{
$next=urlencode("http://www.mysteryzillion.org/gdata/index.php");
$scope=urlencode("http://www.google.com/m8/feeds/contacts/yourmail#gmail.com/full");
?>
Click here to authenticate through Google.
<?
}
?>

Categories