I am able to upload the file using curl on the terminal with the following:
curl https://upload.box.com/api/2.0/files/content \
> -H "Authorization: Bearer {access-code}" -X POST \
> -F attributes='{"name":"tested.png", "parent":{"id":"3804480350"}}' \
> -F file=#/Applications/MAMP/htdocs/BoxappTest/test.png
But when I try to do the same using PHP with the following code:
$filePath=realPath("./test.png");
$xmlfile = file_get_contents("codes.xml");
$codes_data = simplexml_load_string($xmlfile);
$access_token=$codes_data->access_code;
$destination_filename="tested.png";
$id="3804480350";
$ch= curl_init();
curl_reset($ch);
echo "Uploading file...",'<br>';
$post = '{"name":"'.$destination_filename.'", "parent":{"id":"'.$id.'"}}';
$postfields = Array("attributes"=>$post,"file" => "#".$filePath);
$headers= Array("Authorization: Bearer " . $access_token);
curl_setopt($ch, CURLOPT_URL, "https://upload.box.com/api/2.0/files/content");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$output=curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
if(curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
foreach($info as $data => $part) {
echo $data."=".$part, '<br>';
}
echo "File uploaded...",'<br>';
var_dump($output);
It gives me the following output:
Uploading file...
content_type=text/html;charset=UTF-8
http_code=400
header_size=243
request_size=260
filetime=-1
ssl_verify_result=0
redirect_count=0
total_time=1.118914
namelookup_time=0.000738
connect_time=0.022878
pretransfer_time=0.100239
size_upload=335
size_download=0
speed_download=0
speed_upload=299
download_content_length=0
upload_content_length=335
starttransfer_time=1.10153
redirect_time=0
redirect_url=
primary_ip=74.112.185.182
certinfo=Array
primary_port=443
local_ip=10.0.0.188
local_port=50008
request_header=POST /api/2.0/files/content HTTP/1.1 Host: upload.box.com Accept: */* Authorization: Bearer {access-code} Content-Length: 335 Expect: 100-continue Content-Type: multipart/form-data; boundary=------------------------....
File uploaded...
string(0) ""
I have gone over various sites but none of them seem to be right for my problem. No matter what I do, the content_type stays 'text/html'. I have tried to set it in the header and the post fields. But both didn't work. I know I am getting the access codes properly and that they are valid. I am not sure about the curl options though. Setting CURLOPT_VERBOSE or checking for errors does not return anything either. While without the CURLOPT_RETURNTRANSFER option, curl_exec returns true. Can someone help me understand where I am making a mistake here?
I was not able to solve this problem using php itself but using shell_exec() to run the fully form curl command actually worked. So I have stuck to that implementation.
$cmd = "curl https://upload.box.com/api/2.0/files/content \
-H \"Authorization: Bearer $access_token\" -X POST \
-F attributes='{\"name\":\"$dest_name\",\"parent\": {\"id\":\"$parent_id\"}}' \
-F file=#\"$filePath\"";
$result=shell_exec($cmd);
return result;
I hope this helps somebody.
http_code=400 Bad Request.
Try to set your header enctype='multipart/form-data',as upload file use form.
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
more php.net
Related
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.
I am trying to use the zoho inventory api and converting thier sample curl code for use in php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://inventory.zoho.com/api/v1/salesorders");
$vars = array(
"authtoken" => "",
"organization_id" => "",
"JSONString" => '{
"customer_id": 4815000000044080,
}'
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Authorization: Zoho-authtoken ',
'Content-Type: application/json;charset=UTF-8',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
On the page I get this response
{"code":4,"message":"Invalid value passed for JSONString"}
The original code from the docs is
$ curl https://inventory.zoho.com/api/v1/salesorders?authtoken=ba4604e8e433g9c892e360d53463oec5&organization_id=10234695
-X POST
-H "Authorization: Zoho-authtoken ba4604e8e433g9c892e360d53463oec5"
-H "Content-Type: application/json;charset=UTF-8"
-d JSONString='{
"customer_id": 4815000000044080,
}'
I have tried various google searches and it seems that a lot of people have had this same issue and there is no answer given for it yet.
I believe I am trying to add the JSONString in the wrong way
What is the correct way to send the JSONString in php using curl?
Following is the C# code that will not give the following error:
"{"code":4,"message":"Invalid value passed for JSONString"}"` error.
I use a servise http://httpbin.org/post to look, how my post query looks for zoho.
and find an error with symbols \ufeff before JSONString, this is BOM encoding.
So, i change encoding and all right.
Look Example
I has follow step on Path API about how to Authentication User. In the tutorial auth process, user is begin to redirect to the following URL and prompt to grant access:
https://partner.path.com/oauth2/authenticate?response_type=code&client_id=THE_CLIENT_ID
And after that, server will give response as authorization code via URL Address (i have complete this step and got the code).
As from docs explain, Code is should be exchanged for an access token using /oauth2/access_token as long with Client ID and Client Secret (get access_token)
But i don't have any clue how to POST data via cURL to the server, i has try so many curl_setopt() option and combination, but it still give me a nothing.
From the Docs, Request is look like this:
POST /oauth2/access_token HTTP/1.1
Host: partner.path.com
Content-Type: application/x-www-form-urlencoded
Content-Length: <LENGTH>
grant_type=authorization_code&client_id=CLIENT&client_secret=SECRET&code=CODE
And cURL format like this:
curl -X POST \
-F 'grant_type=authorization_code' \
-F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'code=CODE' \
https://partner.path.com/oauth2/access_token
And server will give response like this:
HTTP/1.1 201 CREATED
Content-Type: application/json
Content-Length: <LENGTH>
{
"code": 201,
"type": "CREATED"
"reason": "Created",
"access_token": <ACCESS_TOKEN>,
"user_id": <USER_ID>,
}
To perform a POST request in PHP with cURL, you can do something like:
$handle = curl_init('https://partner.path.com/oauth2/access_token');
$data = array('grant_type' => 'authorization_code', 'client_id' => 'CLIENT', 'client_secret' => 'SECRET', 'code' => 'CODE');
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($handle);
You can then use json_decode($json_encoded) to get an associative array from the server response.
Not sure if you have figured this out yet or not since i see it was from awhile ago, but I just had this problem and this is how I figured it out.
$code = $_GET['code'];
$url = 'https://YourPath/token?response_type=token&client_id='.$client_id.'&client_secret='.$client_secret.'&grant_type=authorization_code&code='.$code.'&redirect_uri='.$redirect_uri;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST,true);
$exec = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info);
curl_close($ch);
$json = json_decode($exec);
if (isset($json->refresh_token)){
global $refreshToken;
$refreshToken = $json->refresh_token;
}
$accessToken = $json->access_token;
$token_type = $json->token_type;
print_r($json->access_token);
print_r($json->refresh_token);
print_r($json->token_type);
Hope that helps
addition to Fox Wilson answer:
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
My goal is to send a POST request to a server and get the proper response.
Note: Angled brackets represent placeholders.
In Terminal, using the following code will provide me the desired response.
curl -u <user>:<pass> -H 'Content-Type: application/xml' -X POST https://<rest of url>
My current PHP looks something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); //$uri is the same that I use in terminal
curl_setopt($ch, CURLOPT_USERPWD,
sprintf('%s:%s', $user, $pass)); //same as terminal user & pass
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$headers = array(
'Content-Type: application/xml', //expect an xml response
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$curl_result = curl_exec($ch);
Using this PHP, I get a 400 Bad Request error.
The verbose information:
> POST <same url> HTTP/1.1
Authorization: Basic YWRtaW5Ac3Bhcms0NTEuY29tOnNwYXJrc29tZXRoaW5n
Host: <correct host>
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue
* HTTP 1.0, assume close after body
< HTTP/1.0 400 Bad request
< Cache-Control: no-cache
< Connection: close
< Content-Type: text/html
Why am I getting a 400 Bad Request error when I use PHP, but not when I use command line? How can I fix this issue so that I get my desired response using PHP?
curl_setopt($ch, CURLOPT_POSTFIELDS, array());
After adding this line, I resolved my problem. In a way, this solution makes sense; but I don't understand why CURLOPT_POSTFIELDS is required. In the PHP documentation, this part should be included under CURLOPT_POST, unless this just accidentally works.
I don't know if this can help you, but for me the Expect: 100-continue looks strange. Take a look at this comment:
http://php.net/manual/en/function.curl-setopt.php#82418
So maybe you can fix it like in the example:
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>
I am using RESTAPI to communicate php client with django server. I have posted json data. The php code is
$arr=array("username"=>"dtthtdas45",
"password"=>"123456",
"email"=>"ramg#ram.com",
"is_active"=>"1",
"is_staff"=>"1",
"is_superuser"=>"1",
"promo_code"=>"1212121",
"gender"=>"m",
"birth_year"=>"1991",
"zip"=>"77707",
"first_name"=>"john",
"last_name"=>"doe",
"current_state"=>"1"
);
echo $data_string= json_encode($arr);
$ch = curl_init('http://localhost:8000/api/ecp/user/?format=json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
How can i call same URL using command line only?
I tried the folowing
curl -H 'Content-Type: application/json' -X POST -d '{"username": "dtthtdas45", "password": "123456","email":"email#email.com","is_active":"1","is_staff":"1","is_superuser",promo_code":"1212121","gender":"m","birth_year":"1991","zip":"77707","first_name":"john","last_name":"doe","current_state":"1"}' http://localhost:8000/api/ecp/user/?format=json
but no luck , it shows the folowing error
curl: (6) Couldn't resolve host 'application'
curl: (6) Couldn't resolve host 'dtthtdas45,'
curl: (6) Couldn't resolve host 'password:'
How can i call same URL using command line only?
I didn't write out all the data pairs, but the following should get you started. I suggest reading more on curl
curl -H 'Content-Type: application/json' -X POST -d '{"username": "dtthtdas45", "password": "123456"}' http://localhost:8000/api/ecp/user/?format=json
Note: Assuming you are doing this for more endpoints, you might want to check out a tool like resty.