i am trying to download a file using box.net using API in php.
As per the documentation i wrote up the code.
but in response i am getting some strange texts.
here's my code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/files/3934139624/content ");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPGET,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: BoxAuth api_key={MyApikey}&auth_token={Mytoken}"));
$result = curl_exec($ch);
die('DIE');
I am getting response something like this:
PK!Ðòš-[Content_Types].xml ¢( ´UËNÃ0¼#ñ‘¯¨qË!Ô´G¨Dù×Þ´‰mÙÛ×ß³IšA›ˆ†^"EÑÎÌÎÎnÆÓ]žEðA[“°QH¯~ÉŸb üv8¼ãÒƒ,0ØdüF¼VÍ„ÇW‘ßZ¯xj-‹b‚cÑcUWP'L8—i)„óQ?H6Mµeå:'ª¸€sÞJZ˳¸¾) ùdü©Xg=ïH[e‡‡,üõÐfL•¥²°Ò.´0´·uPvÒž¦»v˜3Üis¡Mÿ¤³ÎàÉ×ÿSÝ)"à>»DP*ÜNz0êBI‘Û$мfÞºÀi+zŠ P ´0"f3°£\…ȾTºI S‘ÌõŒ«º¾ÇôWš™¦ÚY igï#µÇX6_Ö]7~ fïØˉÈaoÙ.b*lIÆrj)õ,l0Ï%‘b¬ 6ài¢ÕõDÿ_‹Ž…, ¡ ‰Ïó|uœZ^tÙ¢yǯ;!Y,}{ûCƒ³/h>ÿÿPK!¿hJä1>word/rels/document.xml.rels ¢( ¬”ËNÃ0E÷HüCä=qR q'æ>¾ƒ“‘ˆsµà©WÃ-ŽÌEî›nâ>ðÍqã¨Í§y±3ÆóüükeìE±ty’àÕ³üÍ黦ÏÖ¤KLÏhóÊŸi¾IàˆpzÒŽ¹ç?}xÛxx;ùgïÐ¥f7Yô KéMèwÄÆÇÐEïúÃF§³ß9ètÏ7ÌKWxÐ/žñ¡“ùéâ;W…—Ô•¯bú%B×óù§ìv îã㡈“ô£ 8ÜílìÐqq~x|!Ã4Á1Nâ ñaãVš+¾•ËÓr¤ØLe'õc"ójS“Œ(ñR'»>wbriê’6œ,•ôçPøH†.ÔO«<çµ¼G›[¯ ‹Ÿ~ëÈŒcñ)“ )ò<4/nÌ—ôEÛþßpÄÙ÷æ¬Û?xg«\ÖîЃSäÀ•Ç°tÒ(¾‹³ƒwïg˜³ÕKøŒ;ù¾.†ì, l©´ªµÐm¯]‰ŠTíßnÁ¿·ß¤/ë»–ª”짓6õ“^Qð-wô—Qð]6bé à²#ÆûÍ#¡™˜×Fa'™Â†êMî'ÂÛ¿U*XÆÞ/¾\ÁÜl X5HñKÕ˜sØ8EÌ/!вÃÐeq”µ±dº¨É…⛂R—7ЊU¹iØF:h±FÎç¢àõð¾ôÈ!˜&æ',ADSÈP¸L‘M.úìäpow½Ý(¥Ú·R ãpK0è7^;¿Lë4f¤P3Ì…#M s´ï¡Ü:…(#à(1ß;9|÷S½°T4ϹF²ì%“$åÁf“tÖة⼪R&˜nn†)#éóÒfŽBC?‰ð€()ÄÝ(%LNËñ)V^«ÞÛ¶[5+Í>jÀ£WlŽ÷¡¿)ÁoôFBû›CÕ©ëÜ™ÖI¦æÖQ×ƤHX-ijž^ÀDûs“ …Ø}
Can any one tell me how can i handle such kind of response?
thanks in advance.
As per box.net api documentation:
The response to this request will simply be the complete data of the
file itself.
So all you need to save file content locally.
In response header, you need to check content-type, right now it is XML
$result = curl_exec($ch);
$fp = fopen('test.xml','wb');
fwrite($fp, $result);
fclose($fp);
#GBD following comes in response header:
HTTP/1.1 302 Found
Server: nginx
Date: Wed, 14 Nov 2012 09:11:51 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-control: private
Location: https://dl.boxcloud.com/bc/1/85f471520cf611a05025a5f/JolueqOGpciD6dgYhecNBoVpYxkvmYe1ZLheZor6BF4DUBIelMQTkFwYIys3nIibNIIEHUp447tBZLaXDzIbNQ,,/a44510a2b21219463fade41d6b36dabf/
Content-Length: 0
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 14 Nov 2012 09:11:52 GMT
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 19944
Connection: keep-alive
Cache-control: private
Accept-Ranges: bytes
Content-Disposition: attachment;filename="cloud computing proposal.docx";filename*=UTF-8''cloud%20computing%20proposal.docx
X-Content-Type-Options: nosniff
Accept-Ranges: bytes
And saving file in xml also,couldn't b opened.
Related
In curl default content type not changing 'application/json' in output.
$headers = array();
$headers[] = 'Accept: application/xml';
$headers[] = 'Content-Type: application/xml';
$url = url('someurl here');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response=curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
Output:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Request-Time: 295
Date: Wed, 28 Jun 2017 07:41:58 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Connection: Transfer-Encoding
am i done any mistake in that above code? I need output in xml format only.
There is no mistake. Content-type header that you setted is a request header. It defines type of content that you're sending to a server. Which make no sense in GET requests type.
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
...
Is a response headers. Content type here shows format of the server response.
Maybe you didn't pass some parameter that tells server to return xml data instead of json.
Currently working with integrating a new e-commerce API (Swish) but having a bit of a struggle. I'm using PHP and cURL in my app to perform a test-connection to their Merchant Simulator. Code looks as follows:
$post = array(
"payeePaymentReference"=> "0123456789",
"callbackUrl"=> "https://myssldomain.com",
"payerAlias"=> "4671234768",
"payeeAlias"=> "1231181189",
"amount"=> "100",
"currency"=> "SEK",
"message"=> "Kingston USB Flash Drive 8 GB"
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_HEADER, true);
curl_setopt($ch,CURLOPT_URL, 'https://mss.swicpc.bankgirot.se/swish-cpcapi/api/v1/paymentrequests/');
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post);
curl_setopt($ch,CURLOPT_SSLKEY, 'sslkey.key');
curl_setopt($ch,CURLOPT_SSLCERT, 'sslcert.crt');
curl_setopt($ch, CURLOPT_CAINFO, 'cainfo.crt');
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
var_dump($data);
Note: the callback-url in the post-array is different. I have a valid, SSL-domain set there as callback URL.
The response i get when proceeding with above code is this:
HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"0-1448896356000"
Last-Modified: Mon, 30 Nov 2015 15:12:36 GMT
Content-Type: text/html
Content-Length: 0
Date: Sun, 24 Jan 2016 21:07:00 GMT
The 3 parts of the SSL-certificate can be found at Swish's API site if you download the test-tool (Guide Testverktyg). Can anyone please tell me what i'm doing wrong?
Have you tried adding
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
If you post an array directly to the POST, it will transfer as Content-Type: multipart/form-data; boundary=---------------------------- and that's why you are getting this unsupported media type error.
Use http_build_query over your array and you should be fine as it will send data as Content-Type: application/x-www-form-urlencoded
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($post));
I am here with a lot of hope to solve my problem. I have this website i want to login to and access a member only page. so basically php code with cURL to login and then open a member only page. Below is the code i used. But each time i try to access member only page, it asks me to login. So it does not save in the session or cookie that i already logged in.
..........
set_time_limit(0);
$username = 'myemail#yahoo.com';
$password = 'mypassword';
$loginUrl = 'http://radaris.com/login/a.login';
$cookie_file_path = getcwd() . '/tmp/cookie.txt';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 0);
//Set the post parameters
curl_setopt($ch, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_POSTFIELDS, 'email='.$username.'&password='.$password."&remember_me=1");
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
echo "<font color=red>Login</font><br>".$store."<br><br>";
$postfields = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://radaris.com/my/');
curl_setopt($ch, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
//Handle cookies for the login
// Edit: prior variable $postFields should be $postfields;
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
echo "<font color=red>Report</font><br>".$result."<br><br>";
..........
The Result i get is :
Login HTTP/1.1 200 OK Server: nginx Date: Thu, 12 Jun 2014 14:21:01
GMT Content-Type: application/json Transfer-Encoding: chunked
Connection: keep-alive Keep-Alive: timeout=20 Cache-Control: no-store,
no-cache, must-revalidate Cache-Control: post-check=0, pre-check=0
Expires: Wed, 14 Jan 2009 19:00:00 GMT X-Robots-Tag: noindex
{"/Rdf.showError":[["Invalid email or password","login_form"],["Check
your email","login_email"],["Check your password","login_password"]]}
Report HTTP/1.1 302 Found Server: nginx Date: Thu, 12 Jun 2014
14:21:03 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding:
chunked Connection: keep-alive Keep-Alive: timeout=20 Location:
/login?backurl=%2Fmy%2F HTTP/1.1 200 OK Server: nginx Date: Thu, 12
Jun 2014 14:21:03 GMT Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked Connection: keep-alive Keep-Alive:
timeout=20 Vary: Accept-Encoding Vary: Accept-Encoding Set-Cookie:
PHPSESSID=qdg80d48dd17hl879h86v9ruo5; path=/; HttpOnly Expires: Thu,
19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache,
must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Login We
never share or disclose your information!
The above are the headers only. in the 2nd header i get the login form again to login meaning the successful login in the first bit of my code did not save the session that is why when i access member only page, it asks to login.
I am really desperate to get this done right. Thanks everyone in advance.
You're using two separate curl handles, and you never set up the cookie stuff in the second one. Each curl handle is completely independent of each other, so if you don't tell the second handle about the cookiejar/cookiefile you created in the first one, you never actually use the cookie you got from the login request.
Technically, you do NOT have to do one-request-per-handle. A single handle can do multiple requests. The only time it might be easier to start a new one is if you made a complicated custom request with many options set, and it's easier to just start fresh rather than reset those options for the next request.
So your code sequence should be:
init curl
set up cookiefile/cookiefar and other options
do login request
do next next request
close curl
If you don't want to rewrite, then at least add the cookiejar/cookiefile options to the second request.
PHP code file: sms1.php
Located at http://techmentry.com/sms1.php (please visit the link and see the outpur of the below code).
<?php
//Variables to POST
$user = "HIDDEN";
$password = "HIDDEN";
$mobiles = "919999999999";
$message = "test";
$sender = "HIDDEN";
//Initialize CURL data to send via POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/example.php");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&
password=$password&
mobiles=$mobiles&
message=$message&
sender=$sender"
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result"
?>
The output I expected is: The above code should have process this URL: URL HIDDEN
and then return a message ID or appropiate error code.
But the output I got is beyond my expection! There are even no error logs. Please help me :)
You get the code, but you also get the complete response from the server, including HTTP headers.
I get:
HTTP/1.1 200 OK
Date: Wed, 24 Jul 2013 12:24:01 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: max-age=60, private, proxy-revalidate
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 8
Content-Type: text/html
Set-Cookie: PHPSESSID=c9bfcf7ddd3fff9d0a05b34541fbf0a9; expires=Wed, 24-Jul-2013 16:24:01 GMT; path=/
code 105
Try to remove this line:
curl_setopt($ch, CURLOPT_HEADER, 1);
I need to get size of remote file without download. I use this code, but headers from some sites doesn't contain Content-Length: field. How can I get filesize in that cases?
$ch = curl_init("http://wordpress.org/latest.zip");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
$contentLength = 'unknown';
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo $contentLength;
this is result of echo $data;
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 10 Apr 2012 11:32:20 GMT
Content-Type: application/zip
Connection: close
Pragma: no-cache
Cache-control: private
Content-Description: File Transfer
Content-Disposition: attachment; filename=wordpress-3.3.1.zip
Content-MD5: d6332c76ec09fdc13db412ca0b024df9
X-nc: EXPIRED luv 139
If Content-Length header is not present, that means that file size is unknown. In your case you have Content-Disposition header, wich means that downloadable file is an attachment to server response (same as email attachment). So here if you have no Content-Length header you can't get the size.