How to call json from php - php

I have written a php code that should print the response of a json call. But I am getting NULL output. I have checked my json call is working fine from a restclient.
Here is my code
<?php
$username = "user";
$password = "password";
$postData = array(
'username' => $username,
'password' => $password,
'msisdn' => "111111111"
);
$ch = curl_init('http://ip:<port>/xxx/yyy/zzz');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
var_dump($responseData);
?>
Thanks in advance.

Try:
$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON.');
}

okay so i have solved my problem and re-wrote the code. I was actually not providing the correct form of username and password in the json fields which is really a silly mistake.
I am giving my updated code here
`
$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn");
$data_string = json_encode($data);
$ch = curl_init('http://ip:port/call_center/account/general');
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
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
?>`
Thanks everyone.

Related

PHP cURL body does not work with multiple arrays

I need to send a data via cURL in PHP.
There is my POST request and it works with this example (I can post 1 record).
$postData = array(
"username" => "email#domain.com",
"name" => "Name",
"surname" => "Surname",
'role' => 'user',
"disabled" => "false"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getCurlUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt_array($ch,
array(
CURLOPT_POST => false,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'authorization: apikey '.$apikey,
'Content-Type: application/rest+json',
'pincode: '.$pincode
)
// ,CURLOPT_POSTFIELDS => json_encode($postData)
));
curl_setopt($ch, CURLOPT_POSTFIELDS , json_encode($postData));
$httpCode = curl_getinfo($ch , CURLINFO_HTTP_CODE); // this results 0 every time
$response = curl_exec($ch);
if ($response === false) $response = curl_error($ch);
return stripslashes($response);
curl_close($ch);
But I would like to add records from database into $postData array but then it's stops.
This is my database array example:
$postData = array();
foreach ($records = $this->getRecords as $value) {
$row['username'] = $value['email'];
$row['name'] = $value['name'];
$row['surname'] = $value['surname'];
$row['role'] = 'User';
$row['disabled'] = $value['status'];
array_push($postData, $row);
}
json array looks ok but I can't find an error. Or i can't post multiple data and i need to add everything in a loop?
I find a few flaws in the code. You said that you are posting the code but you have set
CURLOPT_POST => false
Also, you have repeated
CURLOPT_RETURNTRANSFER => TRUE and CURLOPT_RETURNTRANSFER => 1
Also, your API might be designed to accept one record but you are trying to send multiple records. If it is designed to accept 1 record at a time you should make the curl call a function and call it in place of array_push. eg:. curlfunction($row);
function curlfunction($postData){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getCurlUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST , 1);
curl_setopt_array($ch, CURLOPT_HTTPHEADER, array(
'authorization: apikey '.$apikey,
'Content-Type: application/rest+json',
'pincode: '.$pincode
)
);
curl_setopt($ch, CURLOPT_POSTFIELDS , json_encode($postData));
$httpCode = curl_getinfo($ch , CURLINFO_HTTP_CODE);
$response = curl_exec($ch);
if ($response === false) $response = curl_error($ch);
curl_close($ch);
return stripslashes($response);
}
and
foreach ($records = $this->getRecords as $value) {
$row['username'] = $value['email'];
$row['name'] = $value['name'];
$row['surname'] = $value['surname'];
$row['role'] = 'User';
$row['disabled'] = $value['status'];
curlfunction($row);
}

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;
?>`

JSON Error on posting Data using PHP

Following is the coding I have done. But after posting the data, I am getting error as:
'message' => string ''from' and 'to' date must be given' (length=34).
Following is my code:
$auth_token=$_REQUEST['auth_token'];
$ch = curl_init('https://api.datonis.io/api/v3/datonis_query/thing_aggregated_data');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'X-Auth-Token:'.$auth_token,
'thing_key:6f2159f998',
'idle_time_required:true',
'from:2016/02/02 17:05:00',
'to:2016/08/29 17:10:00',
'time_zone:Asia/Calcutta',
'Content-Type:application/json',
),
));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
//var_dump($response);
$responseData = json_decode($response, TRUE);
// Print the date from the response
var_dump($responseData);
Actually I also want to get the data but the details are contained in the post request data.
use "CURLOPT_POSTFIELDS":
$data = array("from" => "2016/02/02 17:05:00", "to" => "2016/08/29 17:10:00");
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')

Building a URL with JSON data as a query string parameter value

I have this data
$data = array('username' => 'myname',
'password' => 'mypass'
);
$json = json_encode($data);
How can i pass the json as a variable to a url that looks like this
'http://example.com/login/?data='
this is what i have tried and get '400: data not passed' error
$data = array('username' => 'myname',
'password' => 'mypass'
);
$data_string = json_encode($data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_URL, 'http://example.com/login/?data='); //also 'http://example.com/login/'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Content-Length: ' . strlen($data_string)
));
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
// Exec
$response = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
Any data used in the query string should be URL-encoded.
$url = 'http://example.com/login/' . http_build_query([
'data' => json_encode([
'username' => 'myname',
'password' => 'mypass'
])
]);
http_build_query() will take an associative array of parameters, and apply all the proper encodings, building the whole query string for you.
The URL returned:
http://example.com/login/data=%7B%22username%22%3A%22myname%22%2C%22password%22%3A%22mypass%22%7D
This is possible to do this, you are pretty much there.
$data = array('username' => 'myname',
'password' => 'mypass'
);
$json = json_encode($data);
$url = 'http://example.com/login/?data=' . urlencode($json);
This will be a safe url that can do what ever you want with it.

I want to recive the error code. by the sms host server in php

i want to receive errors from the sms host server
curl_error curl_errno curl_strerror all these function returns error but not in the way i want , mysmshost say that you will receive code like, 202 for wrong mobile number, 301 for wrong authentication, i want to receive those error code please help.
this is my code.
//sending message
$authKey = "my_authentication_key";
$senderId = "sender";
$message = urlencode("Hello Its Working..");
$route = "1";
$campaign = 'Default';
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $number,
'message' => $message,
'sender' => $senderId,
'route' => $route,
'campaign' => $campaign
);
//API URL
$url="http://sms.mysmshost.com/sendhttp.php";
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
//Ignore SSL certificate verification
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//get response
$output = curl_exec($ch);
//Print error if any
if(curl_errno($ch))
{
echo curl_error($ch)."-curl_error<br/>";
$chcode =curl_errno($ch);
echo $chcode;
echo '<br/>error:' . curl_strerror($chcode)."<br/>";
}
curl_close($ch);
echo $output;
Curl_errorno() is not executing, even if i print them without if condition they give no result.
Try this
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$server_output = curl_exec($ch);
curl_close($ch);
print_r($server_output);

Categories