Correct way to send JSON DATA via POST php - php

Is the correct way to send $json data via CURL? in PHP,
I have my $json data in one php, I can send the data information via POST using CURL to my api,??
Do you have some examples, thanks a lot!!

Yes. You can do.
Eg.
// $json_string : Your json String
$ch = curl_init('http://api.example.com/post');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_string))
);
$result = curl_exec($ch);

Please find before post:
http://bavotasan.com/2011/post-url-using-curl-php/
In some key on $data, put your $json.
Example
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
$json = json_encode($your_json); //Your json data
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan",
"json" => $json
);
post_to_url("http://yoursite.com/post-to-page.php", $data);

Related

Remote function calling with paramerters

I am using this function for calling method from one server to another in PHP.
function get_url($request_url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
}
$request_url = 'http://second-server-address/listening_page.php?function=somefunction';
$response = get_url($request_url);
Here I am giving a URL with function name. The question is what if the function receives few parameters? How would we pass parameters to the method on another server using CURL.
Just add
$request_url = 'http://second-server-address/listening_page.php?function=somefunction&funcParam1=val&funcParam2.val
Use these passed parameters in your function
If you want to pass parameter as post request then try this.
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
}
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
post_to_url("http://yoursite.com/post-to-page.php", $data);

How to parse json output?

I tried to parse this url
https://esewa.com.np/epay/transdetails?pid=AddFund-C-11970239- 9625960&amt=100&scd=nprhosting&rid=00C3LF0
{
"code":"00",
"msg":"Success",
"txnDetail": {
"txnCode":"00C3LF0",
"amt":"100.0",
"date":"2015-07-16 23:44:18.0",
"payerId":"dipsnwc#gmail.com",
"status":"COMPLETE",
"pid":"AddFund-C-11970239-9625960",
"txAmt":"0",
"psc":"0",
"pdc":"0"
}
}
Like this
$fields = array(
'pid' => "AddFund-C-11970239-9625960";
'amt' => "100.0";
'scd' => "nprhosting";
'rid' => "00C3LF0";
);
$field2 = json_encode($fields);
$url = "https://esewa.com.np/epay/transdetails";
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $field2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($field2))
);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
//
///Deocde Json
$data = (json_decode($result, true));
var_dump($data);
$message =$data['msg'];
$status =$data['txnDetail']['status'];
echo $message;
echo $status;
Still no output ??
I tried it and worked..
$url = 'https://example.com/epay/transdetails?pid=AddFund-C-11970239-9625960&amt=100&scd=nprsite&rid=00C3LF0';
$data = file_get_contents($url);
$arr = json_decode($data,true);
echo $arr['txnDetail']['status'];
print_r($arr);
Array is incorrect, remove ::
$fields = array(
'pid' => "AddFund-C-11970239-9625960",
'amt' => "100.0",
'scd' => "nprhosting",
'rid' => "00C3LF0"
);
and try
$url = "http://examplesite.com/epay/transdetails?" . http_build_query($fields);
Chuck the POSTFIELDS and HTTPHEADER
curl_setopt($ch, CURLOPT_POST, false);
The parameters are expected to be as GET(as per the link you have provided), keep it simple.
Also check this answer for better understanding on how to send HTTP GET request with PHP CURL.

php curl POST not returnning anything

I have the following php Curl code, to submit a form and get the tables of result
<?php
function httpPost($url,$params)
{
//echo 1;
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output=curl_exec($ch);
curl_close($ch);
//return $params;
return $output;
}
$params = array(
"form_hf_0"=>null,
"searchMode:edit"=>"Births",
"searchSwitch:birthContainer:regNumber:regNumber"=>null,
"searchSwitch:birthContainer:regNumber:regYear"=>null,
"searchSwitch:birthContainer:subjectName:familyName:edit"=>"smith",
"searchSwitch:birthContainer:subjectName:givenName:edit"=>null,
"searchSwitch:birthContainer:subjectName:otherNames:edit"=>null,
"searchSwitch:birthContainer:fatherGivenName:edit"=>null,
"searchSwitch:birthContainer:fatherOtherNames:edit"=>null,
"searchSwitch:birthContainer:motherGivenName:edit"=>null,
"searchSwitch:birthContainer:motherOtherNames:edit"=>null,
"searchSwitch:birthContainer:dateOfEvent:range:edit"=>true,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:day"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:month"=>01,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateFrom:year"=>1788,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:day"=>31,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:month"=>12,
"searchSwitch:birthContainer:dateOfEvent:switchGroup:range:dateTo:year"=>1913,
"searchSwitch:birthContainer:district:edit"=>null,
"search-button"=>"Search"
);
$param1 = array("username"=>"sa","password"=>"1");
echo httpPost("https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0-2.IFormSubmitListener-mainContent-form",$params);
?>
The form link is here:https://lifelink.bdm.nsw.gov.au/lifelink/familyhistory/search?0
I have nothing printed.
Can anyone pointed where is wrong?
The result is here http://ec2-54-213-181-25.us-west-2.compute.amazonaws.com/htdocs/lib/CURL/curl.php
Nothing in the table as normal search with family name "smith", range date 1788 to 1914.

PHP Post JSON value to next page

I want to grab json string, set objects and httpheaders in 1.php (for example). Get these values in JSON format and display in next page (2.php).
I tried to use CURL method. I m very new to PHP. Not sure whether CURL method is the best to POST data.. Session or cookie method no need. Is there any other method other than this to POST data?
1.PHP:
<?php
$data = array($item_type = "SubscriptionConfirmation";
$message = "165545c9-2a5c-472c-8df2-7ff2be2b3b1b";
$Token = "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d6";
$TopicArn = "arn:aws:sns:us-east-1:123456789012:MyTopic";
$Message = "You have chosen to subscribe to the topic arn:aws:sns:us-east-1:123456789012:MyTopic.\nTo confirm ";
$SubscribeURL = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:MyTopic&Token=2336412f37fb6";
$Timestamp = "2012-04-26T20:45:04.751Z";
$SignatureVersion = "1";
$Signature = "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=";
$SigningCertURL = "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem";);
$json_data = json_encode($data);
$ch = curl_init('http://example.com');
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_CAINFO, "/path/to/CA.crt");
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;
?>
2.PHP:
How to post 1.php json value to 2.php.. either through CURL or other posting method.. Tried my best.. cant able to figure out the solution.
Thanks
1.php
$data = array(
'test' => 'data',
'new' => 'array');
$json_data = json_encode($data);
// Only work with your example, curl need full url
$request_url = 'http://teshdigitalgroup.com/2.php';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
print_r($output);
AND 2.php
print_r(file_get_contents('php://input'));
// Response 1.php's request HTTP Header
function parseRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
print_r(parseRequestHeaders());

How to post data using curl and get reponse based on posted data

Here is my code to POST data:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
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);
curl_close($ch);
$json_result = json_decode($result, true);
?>
<p>Your confirmation number is: <strong><?php echo $json_result['ConfirmationCode']; ?></strong></p>
Whereas on domain/server curl.php file code as under:
<?php
// header
header("content-type: application/json");
if($_POST):
echo json_encode(array('ConfirmationCode' => 'somecode'));
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;
?>
But it always return 'none'. Am I missing something?
The actual problem is in grabbing it..
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
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);
curl_close($ch);
echo $result;
//$json_result = json_decode($result, true);
?>
your code for curl.php
<?php
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
/*if($rawData):
echo json_encode(array('ConfirmationCode' => 'somecode'));;
else:
echo json_encode(array('ConfirmationCode' => 'none'));
endif;*/
?>
Since You are sending the data as raw JSON in the body, it will not populate the $_POST variable
Hope this will help you
The function on this link will work.
<?php
function post_to_url($url, $data) {
$fields = '';
foreach ($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
return $result;
}
$data = array(
"name" => "new Name",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
$surl = 'http://mydomain.com/curl.php';
echo post_to_url($surl, $data);
?>
Whereas, on curl.php
<?php
file_put_contents('abc.text', "here is my data " . implode('->', $_POST));
if ($_POST['name']):
print_r($_POST['name']);
endif;
?>
The "correct" Content-Type header for a POST request should be application/x-www-form-urlencoded, but you overrode it with application/json (which is only needed from the server side).
Change your code to below:
<?php
$data = array("account" => "1234", "dob" => "30051987", "site" => "mytestsite.com");
$data_string = json_encode($data);
$url = 'http://mydomain.com/curl.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true); // no need to use custom request method
// ----- METHOD #1: no need to "stringify"
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);
// ----- METHOD #2: or if you really like to JOSN-ify
curl_setopt($ch, CURLOPT_POSTFIELDS, array("json"=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* ------ this will be handled by PHP/cURL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
*/
$result = curl_exec($ch);
curl_close($ch);
$json_result = json_decode($result, true);
?>

Categories