Вы находитесь на странице: 1из 21

LORNAJANE Blog

POSTing JSON Data With PHP cURL


22 Nov
2011 I got this question the other day: how to send a POST request from PHP with correctly-formatted JSON data? I referred to the slides from my web services tutorial for the answer, and I thought I'd also put it here, with a bit of explanation. After all,
publishing your slides is all very well, but if you didn't see the actual tutorial, I often think they aren't too useful.

We can't send post fields, because we want to send JSON, not pretend to be a form (the merits of an API which accepts POST requests with data in form-format is an interesting debate). Instead, we create the correct JSON data, set that as the body of
the POST request, and also set the headers correctly so that the server that receives this request will understand what we sent:

$data = array("name" => "Hagrid", "age" => "36");


$data_string = json_encode($data);

$ch = curl_init('http://api.local/rest/users');
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);

All these settings are pretty well explained on the curl_setopt() page, but basically the idea is to set the request to be a POST request, set the json-encoded data to be the body, and then set the correct headers to describe that post body. The
CURLOPT_RETURNTRANSFER is purely so that the response from the remote server gets placed in $result rather than echoed. If you're sending JSON data with PHP, I hope this might help!

This entry was posted in php and tagged curl, json, post, webservices by lornajane. Bookmark the permalink [https://lornajane.net/posts/2011/posting-json-data-with-php-curl] .

97 THOUGHTS ON “POSTING JSON DATA WITH PHP CURL”

Peter Halasz
on November 22, 2011 at 09:50 said:

Hello Lorna,

I just had the same challenge the other day and got to the same conclusion as your snippet.

Was fairly well documented on the PHP manual as you also pointed out.

Thanks for sharing this little gem of knowledge.

Cheers,
Peter

Sudarshan Wadkar
on November 22, 2011 at 09:57 said:

Thanks, I tried doing something similar style, but didn't set the header to application/json . I don't remember if it worked or not (it was a quick four liner suggestion to a colleague). But what happens if you forget setting the application/json header ?

lornajane
on November 22, 2011 at 15:31 said:
If you don't set the header correctly, the service you are posting to may not understand what it is that you sent - the exact outcome depends entirely on the service though

Sudarshan Wadkar
on November 24, 2011 at 16:25 said:

Thanks Lorna.
Looking at replies below (and I don't know much about script hijacking), I think I will stick setting application/json in the http-header. And if I am writing a server I will (try) not accept simple plain/text.
Ohh BTW, I learned a lot from the slides that you linked in this post. I asked my colleague to read slide 39 - 42 for a quick introduction to SOAP. Pretty interesting stuff !

Angelo R.
on November 28, 2011 at 23:18 said:

One thing to note is that some servers will recognize: application/javascript as application/json as well.

Christian Wenz
on November 22, 2011 at 16:05 said:

many frameworks expect the application/json content type to battle JSON Hijacking.

Evert
on November 23, 2011 at 01:24 said:

Well JSON hijacking would be relevant when sending JSON back in the response body, it has no relevance in the request body.

Christian Wenz
on November 24, 2011 at 07:50 said:

of course - but a server backend could demand that the request contains the Content-type header. JSON Hijacking uses a script tag, which in turn does not allow to set HTTP headers, unlike XmlHttpRequest.

zaadjis
on November 22, 2011 at 17:58 said:

Same thing without curl as a dependency (for the newbies who don't know about the excellent PHP's streams API):

$data = array('name' => 'Hagrid', 'age' => '36');


$data_string = json_encode($data);

$result = file_get_contents('http://api.local/rest/users', null, stream_context_create(array(


'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n",
'content' => $data_string,
),
)));

lornajane
on November 23, 2011 at 07:54 said:

Thanks for adding the streams example, that's nice! Streams are pretty awesome but as you say, they're not as widely used or understood as they should be

vaultdweller
on May 1, 2012 at 07:03 said:

hey lorna do you have any idea i got this error? when use the PHP stream
file_get_contents(http://yoursite.com/test.json): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

vaultdweller
on May 1, 2012 at 07:01 said:

@zaadjis i tried your code, it works but i had a warning, it does post those json data but it doesn't have a response, the warning is this
file_get_contents(http://yoursite.com/test.json): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

Prakash
on November 25, 2014 at 03:01 said:

zaadji your are life saver man. I was trying for this. You made simple. Thanks to you and lornajane...

Virendra Singh
on August 3, 2017 at 18:27 said:

valuable answers for me , thanks alot

Czarek
on November 23, 2011 at 00:48 said:

+1 zaadjis, I was just thinking about the same.


Pingback: Lorna Mitchell Blog: Buchung JSON-Daten mit PHP cURL | PHP Boutique

Anshul Agrawal
on November 23, 2011 at 05:40 said:

Actually, you can trim down the request a bit and keep it simple.

You don't have to specify the content-length. It will be calculated automatically and appended to the headers.

Also, you don't have to declare the request as a post request explicitly. If you are setting the POSTFIELDS option for curl, curl will convert the request type to POST.

Pingback: Lorna Mitchell’s Blog: POSTing JSON Data With PHP cURL | Scripting4You Blog

Matt
on November 26, 2011 at 23:23 said:

Hey Lorna,

Could you give any examples of any of the discussions you elude to on the topic of accepting POST requests with data in form-format?

Cheers
/Matt

lornajane
on November 29, 2011 at 10:31 said:

Matt, I will put it on my list of "things to blog about some rainy day" :)

Pingback: POSTing JSON Data With PHP cURL | PHP | Syngu

Pingback: Post JSON, XML data With cURL and receive it on other end « TechnoReaders.com

Kyle
on November 29, 2011 at 20:39 said:

Thank you very much for this post, I've been struggling as a non-programmer to attempt to submit some basic form data to an API and this helped immensely.

Blake
on December 29, 2011 at 22:06 said:

For those who are having trouble accessing the data that gets posted use the following:

$body = @file_get_contents('php://input')
andrew downes
on May 22, 2012 at 07:09 said:

Thanks Matt. Will try that. And thanks Lorna for the tutorial.

Bryan
on June 26, 2012 at 17:46 said:

You rock!

godie
on March 26, 2012 at 23:02 said:

thanks to this I could send JSON to my REST services

Dustin
on April 11, 2012 at 06:22 said:

This curl example was exactly what I needed tonight. Thanks for sharing.

matteo
on April 14, 2012 at 15:38 said:

hi, i'm a total newbie of posting json, REST services and so on but i need to work out this:
in order to get a file from a website that needs a login to get it, from within my app i have to post to a REST service this:

[code]{
"Username":"String content",
"Password":"String content"
}[/code]
to this url: [code]http://www.***.it/***service/***service/novels/{ID}[/code] where ID is the file id number and etc
trying with http://username:password@www... works for other services but with this service it get "method not allowed"
the webmaster of the site didn't answer me about it and i'm really tired cause i'm stuck with the work at this point... anyone can help me, please? thanks
matteo

lornajane
on April 18, 2012 at 10:50 said:

matteo: it sounds like the service isn't expecting you to POST to that URL, but you'd need to talk to the people who created the service to get more information. Sorry I can't be more help
Siva
on April 16, 2012 at 15:01 said:

PHP4 , curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); is not working. I can't send the JSON variables in the post method using CURL. IS there any other way to do it?

lornajane
on April 18, 2012 at 10:53 said:

I'm afraid I've never used PHP 4 for this type of thing! I don't know what kind support there is for curl, or what kind of "not working" your example is. I think there was some stream support in PHP 4, so you could research how to create the context you need
your content.

You probably don't need me to tell you that PHP 4 is no longer supported; I must strongly recommend that you upgrade.

Nakul
on June 8, 2012 at 06:32 said:

Hi LORANAGANE,
As you explained "how to post JSON data with php CURL". Can you tell me "how to post XML data with php curl."

thanks in advance.

Nakul.

Pingback: Robert McGhee » June 12th

Brayan
on June 14, 2012 at 13:50 said:

Thanks, this was really helpful. :-)

Cheers.

rai
on June 20, 2012 at 10:53 said:

hi lorna,

I tried catching the results on another PHP file, but it returns no results($_POST is empty). Any idea how this should be done?

lornajane
on June 24, 2012 at 22:03 said:
You need to put the URL of the file, as if you were web requesting it, in the curl_init call - and then it will receive the POST vars. Whatever your target file outputs you will get back as the response, so you can debug that way, or use a proxy such as Wiresha
Charles to see what is being sent, or not. Hope that helps!

Pankaj
on August 10, 2012 at 15:51 said:

you can post json as it by also ...

$(ajax){
type:json,
data:datastring,
success:
}

Pingback: Enviando dados JSON usando cURL | PHP Maranhão

Daniel
on September 13, 2012 at 14:24 said:

Hei, thanks, it was a fast and simple way to resolve an action of an api I'm working on.

Gary Paluk
on October 6, 2012 at 11:26 said:

Thanks for posting this. I'd tried a couple of other resources and tried setting curl to send the header that were in-place in the php document however it wasn't working. When I set it up as in your example it started working. :D

Brunno
on November 7, 2012 at 01:01 said:

Hi Lorna,

I call a webservice from a JQuery $.getJSON function, it works fine.


[code]
var p = {
'field1': 'value1',
'field2': 'value2',
'field3': 'value3'
};
$.getJSON('https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?', p, function(data) {
if (data[0]) {
// print results
} else {
// no results found
}
});
[/code]

I am trying to connect from PHP and CURL, however it does not work, it always return false.
[code]
//FIRST TRY
$params = array( 'field1' => 'value1', 'field2' => 'value2', 'field3'=> 'value3');
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch); // return false instead my JSON
// SECOND TRY
$data_string = json_encode($params);
$ch = curl_init('https://https://service:xxx@xxx.xxx.yyyyy.com.xx/service/search?callback=?');
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))
);

$result2 = curl_exec($ch); // // return false instead my JSON


[/code]

What I am doing wrong?

many thanks,

lornajane
on November 13, 2012 at 12:31 said:

There are a couple of things to check. I don't write much JS but your jquery example looks like it's making a GET request rather than a POST request, so try putting your variables on the end of the URL and using GET from PHP?

Also try checking if you get anything from curl_error($ch) as if the server has any more information, you will find it here.

Hope that helps, and good luck!

Mark Thien
on November 14, 2012 at 03:56 said:

only zaadjis methods works for me. thanks a lot zaadjis !

Toby Griffiths
on November 23, 2012 at 17:11 said:

Hey Lorna, thanks for this. Was having an issue with a request to the Open Mapquest API & I think it's because I wasn't sending the Content-Length header.

ShameerIsmail
on January 1, 2013 at 07:50 said:

hi Lorna
Thanks....but what about image posting as json using Curl

patrick
on January 17, 2013 at 16:49 said:

Hi Lorna
Based on your code i did the following but it is not working what could be the problem ?

"Hagrid", "age" => "36");


//$data_string = json_encode($data);
$str_obj_json='{
"method":"SUBMIT","params":{
"batchType":"submit",
"batchId":"alvarons",
"origAddr":"550",
"origTon":2,
"userData":"Movistar les desea Feliz Navidad",
"submits":
[
{
"messId":"mess127_001",
"destAddr":"51975375377"},
{
"messId":"mess127_002",
"destAddr":"51971855080"}
]
}
}';
$ch = curl_init('http://10.10.237.8:21098/SMBULK/BATCH');
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_obj_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: 395',
'Authorization: Basic dGVzdDp0ZXN0',
'User-Agent: Wget/1.12 (solaris2.10)',
'Connection: Keep-Alive',
'Accept: */*')
);
$result = curl_exec($ch);
?>

lornajane
on January 18, 2013 at 10:40 said:

Hard to guess from this example but you are sending JSON as the body while setting the Content-Type header to indication a form submission, set that to "application/json" instead and see if that helps?

Nigel
on January 22, 2013 at 16:07 said:

Very nice, that's just what I was after, no need for all those over the top Libraries for json rpc 2.0

I hacked it a bit so you can work with posted data like so:

$json_req['params'] = $myParams;
$json_req['jsonrpc'] = '2.0';
$json_req['method'] = 'myMethod';
$json_req['id'] = 1;
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_req));

Thanks again!

Ramesh
on April 23, 2013 at 14:10 said:

This page contains json data : https://indexes.nasdaqomx.com/Index/Weighting/NBI

I am trying to scrap that json data using the script :

$data = array('id' => 'NBI', 'timeOfDay' => 'SOD', 'tradeDate'=> date('Y-m-dTh:i:s.000'));


$data_string = json_encode($data);

$ch = curl_init('https://indexes.nasdaqomx.com/Index/WeightingData');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
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($data_string))
);

$result = curl_exec($ch);
if(!$result)
curl_error($ch);
else {
echo "";
print_r($result);
exit;
}
I am getting the page content but not the json output. Please let me know, where I am wrong.

Denis
on July 22, 2013 at 21:59 said:

Thanks!!

annu
on August 2, 2013 at 11:30 said:

I am getting the page content but not the json output. Please let me know, where I am wrong.

Sachin
on July 31, 2013 at 07:28 said:

"CURLOPT_RETURNTRANSFER", this was the exact thing I was looking for to post data to another domain without begin echoed.. came to know by your example. You really saved my day and made my day too.. thanks a lot.

nocdib
on August 3, 2013 at 18:38 said:

Thanks so much for this post. I was stumped for hours until I found it!

E Net Arch
on August 20, 2013 at 23:16 said:

While working with your example, I found that it failed until I changed the JSON conversion line to:
$data_string = "json=" . json_encode($data) . "&";

index.php
------
"isInstalled",
"params" => Array
(
"1" => "3",
"2" => "4",
)
);

$data_string = "json=" . json_encode($data) . "&";


$ch = curl_init("http://localhose/parrot.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$results = curl_exec($ch);

print ($results);
?>
=====

parrot.php
------

Lucile
on September 6, 2013 at 13:06 said:

Thanks ! It helped me a lot.


I didn't write the line with HTTPHEADER and it didn't work. Now it's fine :)

Lucas Costa
on September 9, 2013 at 23:08 said:

Thank you :D

Michael
on September 13, 2013 at 08:06 said:

Great tutorial! Very simple and easy to understand.

janet
on September 19, 2013 at 12:11 said:

Just created a script to get people signup to constant contact mail list from website. This snippet came in handy. Thanks.

Adam
on October 11, 2013 at 23:45 said:

Thank you! Web site is great and this code snippet is very clean and usable.
Eddie
on November 24, 2013 at 07:04 said:

Here is a pure PHP5 solution, http://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php

Roger Qiu
on February 16, 2014 at 16:35 said:

Remember to use mb_strlen($string, '8-bit');

http://mark.koli.ch/remember-kids-an-http-content-length-is-the-number-of-bytes-not-the-number-of-characters

John Larsen
on July 2, 2014 at 09:53 said:

Actually - think the correct is: mb_strlen($string, 'UTF-8');

Ian
on January 12, 2016 at 14:38 said:

'8-bit' is correct as content-length is the number of octets (http://stackoverflow.com/a/2773408/327074) which is specified as 8-bits and separate from bytes to remove any confusion. So your emojis aren't just 1 in terms of content-length :)

Lee Ingram
on March 24, 2014 at 12:09 said:

Thanks Lorna, this was super helpful =)

Sikha Baid
on April 3, 2014 at 05:31 said:

thanks for this....

david parham
on June 26, 2014 at 18:27 said:
trying to get "post json data via api" to work - going nowhere! basic questions:
>the URL i am sending the json data to - what should that page do when it is called?
>what should be on that page? how do i get data there, then calculate using my class, then return the data?
>i feel lost regarding API's. people post things that seem in the middle of the process. please explain it from the ground up. for hours i view posts that do not really cut to the essence of everything that is going on.
>i already have an index.html that sets up an array, then instantiates my Calculate class that has methods for Mean, Median, Mode, and Range - that works fine. BUT,
>how do i "make it available via an API", and provide the input as JSON, and then output a JSON format?

A more complete explanation is here: "Your client has asked you to make this library available via an API. Your API should implement a single endpoint called "/mmmr" with no query
string parameters. When a POST request is called to "/mmmr", a single JSON object will be passed with an attribute called "numbers". "numbers" is a JSON array of n numbers that should be processed. The script should process the mean, median, mode and
range of the numbers and return back a JSON object."

Sample JSON POST body to [single endpoint] /mmmr


[code]
{
"numbers": [
5, 6, 8, 7, 5
]
}
[/code]
Sample JSON Return Response from /mmmr
[code]
{
"results": {
"mean": 6.2,
"median": 6,
"mode": 5,
"range": 3
}
}
[/code]

lornajane
on June 27, 2014 at 14:05 said:

Your page should do:

$data = json_decode(file_get_contents("php://input"));

Inspect that and you should be able to see the data that you sent to the script. HTH!

POULAMI BANERJEE
on August 13, 2014 at 11:39 said:

Hi Lorna,
Here is my code what I did, but it is not working, can you give some explanation?

$data =
array("original_filename"=>$original_filename,"hardware_status"=>$hardware_status,"software_version"=>$software_version,"original_body"=>$original_body,"looqiId"=>$lId,"longitude"=>$lng,"latitude"=>$lat,"battery_voltage"=>$bat,"time_stamp"=>$tim

$data_string = json_encode($data);
//return $data_string;

$ch = curl_init('https://looqi-api.movingintelligence.nl/looqireceiver/');

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))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$response = curl_exec($ch);

//close connection
curl_close($ch);

return $response;

jai
on August 28, 2014 at 21:19 said:

Thanks this helped!

SpirosK
on September 2, 2014 at 09:14 said:

Thank you for your snippet, it saved me ;)

Anish Ghosh
on October 21, 2014 at 15:49 said:

Thanks a lot.

JOhn
on November 1, 2014 at 19:02 said:

$url = 'http://localhost/phalcon-api-oauth2/insertposts/';

//Initiate cURL.
$ch = curl_init($url);

$atoken='wCtmX4HC94yACOLVJVtufqG5C41RcbFHkq5wq2u4';
$jsontoken= array('token' => 'wCtmX4HC94yACOLVJVtufqG5C41RcbFHkq5wq2u4');

$jsonTokenEncoded = json_encode($jsontoken);

curl_setopt($ch, CURLOPT_HTTPHEADER,$jsontoken);

//The JSON data.


$jsonData = array(
// 'token' => 'wCtmX4HC94yACOLVJVtufqG5C41RcbFHkq5wq2u4',
'name' => 'O345345',
'type' => 'mechanicalss',
'year' => '1983'
);

//Encode the array into JSON.


$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.


curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.


curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json


curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

//Execute the request


echo $result = curl_exec($ch);

I m using this but i m getting this error. The request is missing an access token in either the Authorization header or the token request parameter.Please help

Shane Labs
on November 5, 2014 at 17:31 said:

Was running into issues trying to make some API calls to BrowserStack. This fixed my problems instantly. Thanks so much for sharing!!

vikas kumar
on November 10, 2014 at 12:58 said:

Thanks so much for this post. I searched my website but no solution i have found. thanks again

Toney
on February 4, 2015 at 19:48 said:

Lornajane,

Thanks for this article.

Do you think all or part of a JSON string should be url encoded before posting as in your example?

I expect not. I would like to hear your reasoning.


Thanks,

Toney

lornajane
on February 5, 2015 at 20:44 said:

I don't think a JSON string should be URL encoded for POSTing, because it's not being passed in the URL; when you POST it goes into the body of the request so it will arrive safely without encoding. Hope that helps!

Saint Paul
on February 12, 2015 at 10:34 said:

Thank you! work as a charm! You're the best!!

andymnc
on February 19, 2015 at 17:01 said:

Thank you very much for this!

NomanJaved
on March 11, 2015 at 21:39 said:

$data = array("score" => "234", "playerName" => "Noman", "cheatMode" => "false");
$data_string = json_encode($data);
var_dump($data_string);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.parse.com/apps/testapp--6335/collections");
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(


'X-Parse-Application-Id:G1S3htqkA*******O0Lvw8IRKf7IeaNB5jY64',
'X-Parse-REST-API-Key:KQxLUo4sXAh7D*****IdTP3Lxl6YzT6o2jN',
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
var_dump($result);

But i got error


SSL certificate problem: unable to get local issuer certificate

NomanJaved
on March 12, 2015 at 10:31 said:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

this solve the issue

Gopal Rathod
on March 18, 2015 at 09:43 said:

perfect solution
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Sourav Mukhopadhyay
on March 27, 2015 at 17:15 said:

Great article. I was straggling with the error in my code. You saved me. kudos for you.

Peter
on May 26, 2015 at 16:21 said:

Thanks a lot, it was really helpful

Lance Gliser
on June 10, 2015 at 21:32 said:

Thanks for the notice on


curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($contents))
);
It seems that was the issue I was fighting. My server was giving error code 400 malformed for a while before switching that in.

manoj subramanian
on September 21, 2015 at 06:37 said:

i am using above the code but it showing

HTTP Status 404 - Not Found

type Status report


message Not Found

description The requested resource is not available.

Apache Tomcat/7.0.61

Mandar Chitale
on September 22, 2015 at 13:07 said:

Hello Lorna,

Your blog was extremely helpful, I would like to thank you for that. I have a small problem.

I am communicating with web service for adding and updating an element, and on localhost, it works perfectly fine, but on the live server, it is giving me a status 0 error. For adding and updating an element, I am associating a port number with the web
service URL. Here is my code.

$ch = curl_init('http://int.otono-me.com:8999/api/customers/new');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_PORT, 8999);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"X-Auth-Token: " . $_SESSION["Token"]
));

$result = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
if($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Successful\n";
}
curl_close($ch);

echo $result;

On Localhost, the above code works perfectly fine, but on the live server, I get this error:

cURL Error (7): connect() timed out!

Do I need to make certain changes in the above code to ensure that it works with on the live server?

Looking forward for your response,

Thank you,

Mandar CHITALE

lornajane
on September 30, 2015 at 11:49 said:

If the code works on one platform but not on live, it's most likely that you need to request outgoing network access from the live server; it's not unusual for this to be disabled.

Pingback: How to use PHP curl GET and POST with JSON web services | p6abhu

Vikram
on March 3, 2016 at 02:28 said:

Thanks lorna,
This snippet was really usefull. :)

gaurav
on March 7, 2016 at 07:45 said:

thanks very useful saved a lot of time

Marcelo
on April 25, 2017 at 07:48 said:

Thanks a lot buddy!

ramesh chauhan
on April 25, 2017 at 12:10 said:

this is very helpful for me thanx for this post

Davinder
on July 6, 2017 at 08:14 said:

This is correct way people. Its woking

Geoff
on August 29, 2017 at 18:25 said:

Perfect. Thank you!


Leandro
on November 18, 2017 at 19:45 said:

Very good! Thanks a lot!

Arun Verma
on December 12, 2017 at 06:52 said:

Nice post, it helped me.


Thanks for posting

Вам также может понравиться