I am using cURL to interface with an API. What I wanting to do once I done what I need to with API is output the APIs response.
<?php
/*
* Server REST - user.login
*/
$input = file_get_contents("php://input");
$xml_input = simplexml_load_string($input);
$xml_arr = json_decode(json_encode($xml_input, TRUE));
// REST Server URL
$request_url = 'http://xxx.localhost:8888/api/v1/user/login.json';
// User data
$user_data = array(
'username' => $xml_arr->Username,
'password' => $xml_arr->Password,
);
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE); // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_code == 200) {
$logged_user = json_decode($response);
}
else {
$http_message = curl_error($curl);
return http_response_code(401);
}
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
if($xml_arr->Action == "Delete"){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://xxx.localhost:8888/api/v1/logic_melon/' . $xml_arr->JobReference);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
} elseif($xml_arr->Action == "Add") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://xxx.localhost:8888/api/v1/logic_melon');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_arr));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
}
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 200)
{
// Convert json response as array
$response = json_decode($response);
echo $response;
}
else
{
// Get error msg
$http_message = curl_error($curl);
}
The api returns a response code and an message, how would I output this to my user? return $response doesn't seem to do the job.
Related
I need to make curl request via PHP to the same local virtualhost url. Its really simple. If I make it via Postman or in command line it takes miliseconds. But as I run it in PHP it is still loading without response. I make a log to file after each step so I can say the code stops after Debugger::log(5555555555555).
This is the code:
public function sendRequest(string $url, array $data = null, $method = 'GET')
{
$url = $this->apiUrl . $url;
$ch = curl_init($url);
$json = json_encode($data);
Debugger::log(2222222222222);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
Debugger::log(2222222222222);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
if ($method == 'POST' or $method == 'PUT') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
}
Debugger::log(33333333333);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_PORT , 80);
Debugger::log(44444444444);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiKey,
//'X-API-Token: v4yWSYY2Od7-iA6Vi3e8fRNWMkvii-eF',
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
Debugger::log(5555555555555);
$output = curl_exec($ch);
Debugger::log(6666666666666);
if( curl_errno($ch) ) {
Debugger::log(curl_error($ch), Debugger::EXCEPTION);
throw new \Exception( curl_error($ch) );
}
Debugger::log(77777777777777);
$header = curl_getinfo($ch);
Debugger::log(88888888888888);
curl_close($ch);
$return = array("header" => $header, "output" => $output);
return $return;
}
I am trying to add attachment url in crm. I am flowing this documentation . But i got error !
This is my code :
$zoho_url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$post['attachmentUrl'] = $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_URL,$zoho_url);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$headers = array();
$headers[] = "Authorization: ".$authtoken;
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$err = curl_errno($ch);
curl_close ($ch);
if ($err) {
$result = $err;
} else {
$result = $response;
}
print_r($result);
This is response :
{"code":"INVALID_REQUEST","details":{},"message":"unable to process your request. please verify whether you have entered proper method name, parameter and parameter values.","status":"error"}
I made this code for attach a file in a zoho record.
//Get the oauth Token
$accessToken=getCurrentAccessToken();
// files to upload
$tmpfile;
$filename;
$type;
foreach($files as $file){
$tmpfile = $file['tmp_name'];
$filename = basename($file['name']);
$type = $file['type'];
}
$cfile = new CURLFile(realpath($tmpfile),$type,$filename);
$post_data = array (
'file' => $cfile
);
$url = "https://www.zohoapis.com/crm/v2/$module/$id/Attachments";
$headers = array(
'Content-Type: multipart/form-data',
sprintf('Authorization: Zoho-oauthtoken %s', $accessToken)
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
return $response;
i've create a php function to make a post json data request using curl
My Code :
$url = 'http://77.42.154.142:90/home/test/GetNewCustomer';
$data = array("UpdatedOn" => "1/23/2004 1:00AM","CreatedOn" => "1/23/2015 1:00AM");
$fields = json_encode($data);
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'sduser: 34EE0A61-F3A5-4E21-86D3-C7B7DAF9C8F9913982A9-3025-4C37-8093-B664B9310F91',
'Content-Length:'.strlen($fields)
));
curl_setopt($post, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($fields)));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//curl_setopt($post, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($post);
// for debugging
var_dump(curl_getinfo($post), $result);
// if(false === $result) { // request failed
// die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
// }
curl_close($post);
But i've got this response The parameters dictionary contains a null entry for parameter
Any Suggestion ?
When I execute below code it work fine.
$url = "https://api.mongolab.com/api/1/databases/$DB/collections/$COLLECTION?apiKey=$MONGOLAB_API_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data),
)
);
echo $response = curl_exec($ch);
$error = curl_error($ch);
echo $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_code == 200)
{
$response1=json_decode($response);
echo("<pre>");print_r($response1);echo("</pre>");
}
else
{
echo "Fail";
var_dump($data);
var_dump($status);
}
above work well,it insert one record to mongolab database and return Object id but when execute below code it return null response without any error.
I have check all that thing are right but why response is null.
$url = "https://api.mongolab.com/api/1/databases/winebook-dev/collections/persons?fo=true&q={'email':'$email'}&apiKey=".MONGOLAB_API_KEY;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$data = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status == 200)
{
$data1 = json_decode($data);
$len = count($data1);
if($len > 0 )
{
echo "This email already resistered.";
}
else
{
$url = "https://api.mongolab.com/api/1/databases/$DB/collections/$COLLECTION?apiKey=$MONGOLAB_API_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data)
)
);
$response = curl_exec($ch);
$error = curl_error($ch);
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_code == 200)
{
$response1=json_decode($response);
echo("<pre>");print_r($response1);echo("</pre>");
}
else
{
echo "Fail";
var_dump($data);
var_dump($status);
}
}
}
if any one know solution then answer this question suddenly.
thanks in adv.
For days I tried to implement a number of solutions from the gcm & php thread here to get my server to send a message to the GCM server and then to my Android device. My call to curl_exec($ch) kept returning false. After a few days of racking my brain, reading and searching the web it seems I finally figured it out. I had to use GET instead of POST, I found that here, and I had to NOT verify the SSL. (I can't remember where I found that...)
I hope this helps someone who's having the same problem. And please, if anyone can improve upon this their corrections are more then welcome.
This is what was suggested by the thread linked to above:
$ch = curl_init();
// WRITE MESSAGE TO SEND TO JSON OBJECT
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error</p>";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
echo "<p>httpcode: " . $info['http_code'] . "</p>";
}
curl_close($ch);
For me to get this working I have to implement the following.
$ch = curl_init();
$message = '{"data":{"message":"here is the message","title":"message title"},"registration_ids":["'. $reg . '","'. $reg2 . '"]}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_URL, $gcmurl);
/*
* COMMENT OUT THE FOLLOWING LINE
*/
*//curl_setopt($ch, CURLOPT_POST, true);*
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// WRITE JSON HEADERS
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization:key=' . $apiKey)
);
/*
* ADD THESE 2 LINES
*/
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
if(!$result > 0){
echo "<p>An error has occurred.<p>";
echo "<p>ERROR: $curl_error";
}
else{
$json_return = json_decode($result);
echo var_dump($json_return);
$info = curl_getinfo($ch);;
}
curl_close($ch);
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$data = json_encode($input);//Your json data...
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
switch($method)
{
case 'GET':
curl_setopt($handle,CURLOPT_HTTPGET,true);
break;
case 'POST':
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case 'FILE':
curl_setopt($handle, CURLOPT_HEADER, 0);
curl_setopt($handle, CURLOPT_VERBOSE, 1);
curl_setopt($handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($handle, CURLOPT_POST, true);
echo $data;
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
break;
}
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
return $response;
Have you uncommentted ;extension=php_curl.dll in your php.ini(remote or localhost)
This worked for me cause it returns :
{"multicast_id":8298406095978893272,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1439084688510033%9bd2607ff9fd7ecd"}]}
but I can't receive the notification on the client side.
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
require_once __DIR__ . '/db_config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
// $fields = array(
// 'registration_ids' => $registatoin_ids,
// 'data' => $message,
// );
$fields = '{"to":"caFPICUdKKM:APA91bEJW2vtQHy5IQcOM88WlT5zazf-D9LExvOaSGgAOHqSkHBeHWP34KV1BEKLA9n932BrZXTCwJajug4kcX2LrURY1NJPb9V-vmis1Ra8bo2Zw2BgIIXrfoDbM42Ip6RN_ic1C6eU","data":{"title":"Testing","body":"Success","icon":"R.mipmap.ic_launcher"}}';
$headers = array(
'Authorization: key=' . GOOGLE_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));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>