get data with CURL and JSON - php

i am trying to get data using Curl
i was trying to get best result but i got
but my goal to get specific line NOT all the lines.
see my code and please help to get the result with
"routing" AND "tot_dist" Other variables NO
here is my code
<?php
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = 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_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
echo httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
// I WANT TO GET THE RESULT WITH ROUTING AND tot_dist ONLY LIKE THIS
//OOMS DCT KASIN DCT OOSA
//459.5
?>
This result i got
{"rc":"100","rmsg":"OK","gc_dist":459.2,"routing":"OOMS DCT KASIN DCT OOSA","tot_dist":459.5,"legs":[{"wt":"A","id":"OOMS","lat":"23.6002","lon":"58.2836","freq":"","via":"","brg":"0.0","dist":"0.0","name":"MUSCAT INTERNATIONAL"},{"wt":"W","id":"KASIN","lat":"20.3147","lon":"55.9617","freq":"","via":"DCT","brg":"214.7","dist":"235.8","name":"KASIN"},{"wt":"A","id":"OOSA","lat":"17.0387","lon":"54.0913","freq":"","via":"DCT","brg":"209.6","dist":"223.6","name":"SALALAH"}]}
but i need only "Routing" and "tot_dist"

Once you make a request, you will get all the data. You can then select what you need. Here is what your code should look like to select only routing and tot_dist
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $l => $v)
{
$postData .= $l . '='.$v.'&';
}
$postData = 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_HTTPHEADER,
array(
'Accept:application/json'
)
);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
$params = array(
"id1" => "OOMS",
"id2" => "OOSA",
"routing" => "",
"dbid" => "2006",
"k" => "",
);
$data = httpPost("http://rfinder.asalink.net/free/autoroute_rtx.php",$params);
echo $data['routing'] . "\n";
echo $data['tot_dist'] . "\n";

Related

Php Variable is null when i pass it to the array

I am trying to send user-specific web notifications with onesignal and i solved everything except this variable null problem.
I use that variable multiple times and there is no problem except these lines:
<?php
if(isset($_POST["sub"]))
{
$my_variable= $_POST["t1"];
$SQL = "some sql here";
if (mysqli_query($db, $SQL)) {
echo $my_variable;
echo "<br>";
function sendMessage(){
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => "$my_variable")),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
The result is :
1 JSON sent: {"app_id":"5b0eacfc-3ac8-4dc6-891b-xxxxx","filters":[{"field":"tag","key":"key","relation":"=","value":"null"}],"data":{"foo":"bar"},"contents":{"en":"test message"}}
I tried so many variations with/without quotas , json_encode() function but couldn't pass that variable to that array.
Your variable is out of scope.
You define $my_variable outside of the function sendMessage(), but proceed to try and use it within the function, without passing it as a parameter.
This can be fixed with the following:
function sendMessage($filterValue)
{
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => $filterValue)),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($my_variable);
$return["allresponses"] = $response;
$return = json_encode( $return);

Not able to send push notifications in android even after getting success1 through my PHP script

My PHP script looks like this:
<?php
$reg_id = "d8Sq53-gteU:APA91bGFcbSrcWY6J9fVBhUJVci4YHgktjoTOTbRjMXi7uY6ss-kLM39GpSt16cMmwsm2k4n9y3_YrcyBT7o9bpsN2QFS_bVceMcV-WThbThXMCWSiwaaP7p5LAJlb_01mzPbHb6xq1X1";
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $reg_id ,
'priority' => "high",
'data' => array(
"title" => "Android Learning",
"message" => "Test",
"image"=> "dsdsd",
"tag" => "dsdsd"
)
);
$headers = array(
'Authorization:key = AIzaSyC6ld4WBRmk8W6DZgMqevu1Na3dcQdQDBIA ',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
print_r($result);die;
?>
This is the response I am getting:
{"multicast_id":7558168491201020947,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1484883356821016%9bd11ceef9fd7ecd"}]}
But in Android I am unable to get the data that I am posting through the notification. Is there a problem with PHP script that I am using, Is the response that I am getting through PHP script correct. Or there is some problem with the android code. Can anyone help me please.
**Please check below .php file it will working fine for me.**
**You just need to pass firebase id "fcm_token" parameter to this php file**.
<?php
require_once __DIR__ . '/config.php';
// need to pass Firebase Register ID.
$registration_ids=$_POST["fcm_token"];
$title='hello';
$message='Please check the Details';
$is_background=FALSE;
$image='';
$payload='Its Payload';
$timestamp='10:15';
$arr = array('title' => $title, 'is_background' => $is_background, 'message' => $message, 'timestamp' => $timestamp, 'image' => $image,'payload'=> $payload);
$arr1 = array('data' => $arr);
$json = $arr1;
$fields = array('to' => $registration_ids,'data' => $json,);
//echo json_encode($fields);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_API_KEY,
'Content-Type: application/json'
);
// 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_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
echo 'its Not done bro';
}else{
echo 'its done bro';
}
// Close connection
curl_close($ch);
?>
Finally got the code which is working for me-
`
$filename = 'Fav_Icon.png';
$title = "thisis title";
$coupon_id = 1;
$url = 'https://fcm.googleapis.com/fcm/send';
$msg = array
(
'message' => 'We have added a new Coupon. Please have a look !!!',
'title' => $title,
'smallIcon' => base_url().'uploads/icons/'.$filename,
'type' => 'Coupon',
'coupon_id' => $coupon_id
);
$res = array();
$res['data']['title'] = "Coupon Name";
$res['data']['message'] = "We have added a new Coupon. Please have a look !!!";
$res['data']['image'] = base_url().'uploads/icons/'.$filename;
$res['data']['tag'] = "Coupon";
$res['data']['coupon_id'] = $coupon_id;
$fields = array(
'to' => $reg_id ,
'priority' => "high",
'data' => $res
);
$headers = array(
'Authorization:key = AIzaSyC6ld4WBRmk8W6DZgMqevu1Na3dcQdQDBIER ',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
print_r($result);
return $result;
?>`

pass html form data to json php string

I've been able to perform a parse to post data to my api using this format:
Working sample:
<?php
$appId = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$private_token = 'XXXXXXXXXXXXXXXXXXX';
$geo_post = "/api/v1/geofence/";
$name = "Home";
$latitude = 38.646322;
$longitude = -121.185837;
$radius = 50;
$data = array(
"name" => $name,
"location" =>
array( "latitude" => $latitude, "longitude" => $longitude),
"matchRange" => $radius
);
$data_string = json_encode($data);
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com' . $geo_post );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = trim(curl_exec($ch));
curl_close($ch);
//print_r($content);
?>
Sample with Error message:
<?php
if (isset($_REQUEST['add_new'])){
$appId = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$private_token = 'XXXXXXXXXXXXXXXXXXXXXXX';
$geo_post = "/api/v1/geofence/";
$name = $_GET['db_geofencename'];
$latitude = $_GET['db_latitude'];
$longitude = $_GET['db_longitude'];
$radius = $_GET['db_radius'];
$data = array(
"name" => $name,
"location" =>
array( "latitude" => $latitude, "longitude" => $longitude),
"matchRange" => $radius
);
$data_string = json_encode($data);
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com' . $geo_post );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = trim(curl_exec($ch));
curl_close($ch);
print_r($content);
?>
As you can see I'm using a string in my $data array, so i'm trying to capture the information from the form and pass it to the $data array, but if I use $_GET or $_POST i end up with an error message:
{ "success": false, "errorMessage": "The request content was malformed:\nExpected String as JsString, but got null", "errorCode": "BadRequest" }
what is it I'm doing wrong?
So best i can think of is convert(type cast) your $latitude and $longitude into floating numbers. Don't depend on php auto type casting as some times internally it will keep it as string and i guess that api want $latitude and $lon... as floating numbers not strings.

Curl - how to handle the response

I am using this to send some info to another website and its working fine
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);
$result = curl_exec($post);
curl_close($post);
}
$data = array(
"api_key" => "****",
"api_password" => "****",
"notify_url" => "www.mysite.com",
"order_id" => "$orderid2",
"cat_1" => "$cat_1",
"item_1" => "$item1",
"desc_1" => "$desc_1",
"qnt_1" => "$qty1",
"price_1" =>"$up1",
"cat_2" => "$cat_2",
"item_2" => "$item2",
"desc_2" => "$desc_2",
"qnt_2" => "$qty2",
"price_2" => "$up2",
);
post_to_url("http://website2.com/submitorder.php", $data);
When website2 receives the info its sending back an xml responce "OK-Data Received" which appears on my page. Is there something I can do to stop this message being shown on my page so the person using the site doesn't see it?
You have to set the CURLOPT_RETURNTRANSFER setting :
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
That way, curl_exec($c) will return the output instead of passing it to the browser.
CURLOPT_RETURNTRANSFER
TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
Set the option to:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

How do I use arrays in cURL POST requests

I am wondering how do I make this code support arrays? At the moment the images array only seems to send the first value.
Here is my code:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images[]' => urlencode(base64_encode('image1')),
'images[]' => urlencode(base64_encode('image2'))
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//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, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
and this is what is received at the api
VAR: username = annonymous
VAR: api_key = 1234
VAR: images = Array
array(3) {
["username"]=> string(10) "annonymous"
["api_key"]=> string(4) "1234"
["images"]=> array(1) { // this should contain 2 strings :( what is happening?
[0]=> string(8) "aW1hZ2Uy"
}
}
What is happening to the second value in images[]?
You are just creating your array incorrectly. You could use http_build_query:
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
$fields_string = http_build_query($fields);
So, the entire code that you could use would be:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//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, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);

Categories