HTTP POST a JSON array using PHP/CURL - php

I'm trying to send a JSON array to an API via HTTP POST, get a response and print it.
I tried using cURL to do so, but it doesn't seem to work.
I simply get zero response, a blank page.
My request:
<?php
$data = array(
"login" => "myLogin",
"password" => "myPassword",
"id" => "12345",
"tag" => "test"
);
$json_data = json_encode($data);
$ch = curl_init('URL/api/mylogin');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
$result = json_decode($output);
echo $result;
?>
The response I should be getting:
{"status": 200, "message": "OK", "login_key": "abcdefh532h235yh"}
any idea why I'm not getting any response?
(this works ok when I manually test it using a test REST client)

Try this #rani now you can get response.
$url = 'URL/api/mylogin';
$ch = curl_init($url);
//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // RETURN THE CONTENTS OF THE CALL
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_USERPWD, 'myLogin'.':'.'myPassword');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
or pass key as a password in CURLOPT_USERPWD.

Related

I am not getting readable format data using CURL?

Below is my code
$url = 'http://api.walmartlabs.com/v1/feeds/bestsellers?apikey=xxxxx';
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/xml',
'Connection: Keep-Alive'
));
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
exit;
my output is ....
��ks�Ȓ&�}~EE�������;N���ִdkM�=gg6� ��(��;����*��fQ���'�E#�*+++�����!k����`��_�o���f�g�f8碒Es|��k��B�$����_�����|v6-���*�����\=h� ���<���5ƁC�Ƣ�e�<͔�� ��e����Ue�����W��zZV́��*�7YYP#?�ͯ�/�_�+ /`yY\�\�MV\����U&k�L0z��Y�(V���f�]e͔5Ӭf�#v)��JJz�8f�SYK6��Hd�.r��敬k�E�ʂ�b���K�mE?UЦhX�]Y����Le�=Y"%�,�ضh~�Y$c���P?L>%R��Ǣl~e���?���h{C���Bu��i 4g)����岻�1Q0�X΀��5+.�F4�Q$��ٟ�%t��G�ihg�ț[��|�+��iO� �W�^�$�fS��B�Y�d�j[VK��1�M��4�����d~�IQ���+������X�pϘT� A���eU�r�<��)Q ���o�;�B�-�r��G�F �}��K|����/̌���,A�0)�%�Kl��^��z�N�G����c��"ޡU�V:.⡅�-���O(������Z���<�O�ט~mMУ������7�y�΃kt��-���lo��nPd)�����foJ��׸�Z�;j��D����v�z)�KY�.5��,*����t}�4������_�|&���T��r�#�j�LL�tc�{Q�s�"xn�m+ ���,+�?Xc�NK�q'�/�����3,ב�H��s./�^&�+ Tk����}�4������R�O�2������jW���梺�_�����S��ZO�J�8�D���*�zγ�c���X�=�>�5��b'�a��{�����L^��K\��ݲl÷Ǿ�,��o��#�:p%��^D���q ��fs�h���ۃg�oOͿ����ڻ��uD�\]]�v�~���Gibd'%���SW�Z�m�4���������#��=���u�e1�y`��f9��u��4�ρLH�T�T�)�����B)w��n?/' ��)�ɦ��2��kX��R*�ۗ����6a�&*S��&�فaFT�=��Dj-oR�踉�= [ ���v=�n�å���4��W�6���`�K�"_v�m���0f��X��6���`�cz�ѢH�k��s)#�]';h�o�DQoe2�2�H��mwoղh�*����*�����jy*�i������)D��_�dA�gz���Rm'�y d|�|u�u�V� ��/�����"w���jz�t����mw�ؾ�и&3H��sWɇ�A���� "�-";�E�� �k�9��:_v��(G��T�/�5�Qq�^C�ՋD}]62*ˏ#�\�]�21���%�Px8E����?�D��X#��P�w<#����.vz��,��}v���|�+�2�:fg�X�j#���V��:�o9V"�6��x^k�;�`m��E���ӟO��T��/����T��ʸD��;��{�Q}�-��{Ѩ�� ��eY�i���D����Y����W�=�Œ�Yx�~��&}�.�:�ޮ�����Y�1��rЉ�!Y��\���h� ,���d�kDV���[V�#k}�>��t�������E$G�l�<�4b�~?�}�vg�ϲ`�n� {�%�b*P�WLR�/C�ݞ�nG}+:��(��x�sД��<�`#X)E�S��#ۅ�q�UU�m���,�XR�02� �&�d���دV��^x]^���.%ި4��F4�-�1;n��{��Au歏_�#I ?��S�.|���� �Rv S�I��Z���L�)ș�O� 4R�`G8�Y���$����|¬��ݵ7�ޚȸ�,���.�.�k���� pB���S�k���H��0v��-C�ش�莇{�U�n��ߩe7b�E��o��ul�1��E��8y��o��M-����6�2kd<-#W�X���o�UZ��2U4�-�����h��K)������0D��r6i�F�U����C�=6�\>��⃏� ��مZyD�fb�Ǖ�ޏF�*�x���A�c��5st���xl.|�s/�"��#< \�[��ؾ�!��A3K�$��F6�dbٞ�$"6��������c�-��������4�2����#w�z�s#��?���{��?>��;8�X�alJ�A���������C���l}pn��v���=���N��_2w3�2?2�ȣ/
please help me to solve this issue...
Try this:
XML is now deprecated and JSON is the supported format. The api returns data gzipped. So, you will have to decode the response appropriately.
$url = 'http://api.walmartlabs.com/v1/feeds/bestsellers?apikey=<apiKey>&format=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Encoding:gzip'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
print_r(gzdecode($data)); // un-gzip before using it
Hope this helps.

Symfony2 Authentication via HTTP headers

I have Symfony2 app running, that has login mechanism implemented.
However I need somehow to send request from other app, that checks whether requested URL exists on that system:
For example there's request http://myapp/order/1111 that I need to check whether it returns 200 OK header or 404 Not Found status;
When I send request it's unauthorized and get's redirected to login page /login which is returns 200 OK status header.
What I need is to somehow safely bypass login mechanism. Is there a way that I could add login credentials to request, or create additional login method?
EDIT:
As suggested in comments, I tried to use curl. But I can't figure out how make it work. Here's what I'v got, but It doesn't work.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/en/login');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_POST, true);
$html = new DOMDocument();
$html->loadHTML(curl_exec($ch));
if (curl_error($ch)) {
echo(curl_error($ch));
}
$csrf_token = $html->getElementById('csrf_token')->getAttribute('value');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/en/login');
//curl_setopt($ch, CURLOPT_REFERER, 'http://localhost/en/login');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'_username' => 'login_username',
'_password' => 'login_password',
'_remember_me' => 'on',
'_csrf_token' => $csrf_token
)));
curl_setopt($ch, CURLOPT_POST, true);
$result = curl_exec($ch);
if (curl_error($ch)) {
echo(curl_error($ch));
}
echo $result;
curl_close($ch);
Any suggestions, how to work with curl on this case?
I wrote a solution to this problem if anyone else struggling with this:
$ch = curl_init();
//get login form
curl_setopt($ch, CURLOPT_URL, $login_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_path);
//parse html to get csrf_token, I added id attribute to it for easier retrieving
$html = new DOMDocument();
$html->loadHTML(curl_exec($ch));
$csrf_token = $html->getElementById('csrf_token')->getAttribute('value');
if (curl_error($ch)) {
throw new Exception(curl_error($ch));
}
//send post request to login_check with parameters (csrf_token included)
curl_setopt($ch, CURLOPT_URL, $check_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'_username' => $username,
'_password' => $password,
'_remember_me' => 'on', //if you use remember me functionality
'_csrf_token' => $csrf_token
)));
curl_exec($ch);
if (curl_error($ch)) {
throw new Exception(curl_error($ch));
}
//request login protected urls
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_exec($ch);
if (curl_error($ch)) {
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
curl_close($ch);
//I used this code in a function returning url and http_code for further processing
return array(
'url' => $info['url'],
'http_code' => $info['http_code']
);
I was having a problem with localization. I used to pass login_check url with locale like this http://localhost/en/login_check, by removing locate I fixed the problem: http://localhost/login_check

POST Request using CURL and PHP not working properly

I am trying to programmatically process my statement using the form at http://nlp.stanford.edu:8080/corenlp/process. I have the following code snippet in PHP/CURL. However, instead of processing the statement, it is returning the HTML for the form - as if the post parameters are not being sent. I checked that I am sending the required paramaters. Can someone guide me as to what I am doing wrong?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://nlp.stanford.edu:8080/corenlp/process");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/14.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'outputFormat' => 'xml',
'input' => 'Here is a statement to process',
'Process' => 'Submit Query'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
echo $result;
You have to convert the $data array into a string... Also, Be sure to urlencode() the individual values.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://nlp.stanford.edu:8080/corenlp/process");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/14.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
"outputFormat" => "xml",
"input" => "Here is a statement to process",
"Process" => "Submit Query"
);
$data_string = "";
foreach($data as $key=>$value){ /// YOU HAVE TO DO THIS
$data_string .= $key.'='.urlencode($value).'&'; /// AND THIS
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
echo $result;

Error in image upload

I want to post some data including a image.I am using curl in php for this.My code is below-
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux i686; rv:6.0) Gecko/20100101 Firefox/6.0Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, 'http://postacity.co.uk:8080/shine/pp/upload/');
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
'creatorid' => '119',
'userfile' => '#/temp/fgf.jpg',
'notice' => 'Image1',
'catid' => '1',
'title' => 'bookofzeus',
'boardid' => '332',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
if(curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
else {
echo $response;
}
}
Every time i am getting the same error
Error: failed creating formpost data
Am i doing any mistake.I have searched for this problem but still no solution found.
The path to the file is the problem: '#/temp/fgf.jpg'
You should take a look at this bug gescription: Bug 50060 - failed creating formpost data if post array value starts with #
The solutions of this problem for example at php freaks.
And use absolute path to the files.
Refer this its working
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, _VIRUS_SCAN_URL);
curl_setopt($ch, CURLOPT_POST, true);
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"#/path/to/myfile.jpg",
"username"=>"foobar",
"password"=>"secret",
"submit"=>"submit"
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
?>
Also refer this url's
http://joshhighland.com/blog/2010/11/27/using-curl-and-php-to-upload-files-through-a-form-post/
http://blogs.digitss.com/php/curl-php/posting-or-uploading-files-using-curl-with-php/

Get html of https after logging in

I would like to get the html of the page. After some google-ing, i found following code, which isn't working.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$passwd");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo $output;
edit: something like this then:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_POSTFIELDS,'username='.urlencode($username).'&passwd='.urlencode($passwd));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/my_cookies.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/my_cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_REFERER, "");
$output = curl_exec($ch);
echo $output
This just shows the target page, it doesn't log in, nor does it return the html code.
edit 2: now tried with $data = array('username' => $username, 'passwd' => $passwd); and curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
This shows the same as above + an error: Request Entity Too Large
That page does not use HTTP Basic Authentication.
You need to make an HTTP request to match what submitting the form would sent, then you need to process the response (which will probably involve storing cookies).

Categories