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;
}
Related
I want to change profile image another application curl request i am trying below code can anyone help me please
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}
As Anoxy said, you need to put in the header the Content-Type :
$viewer = Engine_Api::_()->user()->getViewer();
$apiData = array(
"email" => $viewer->email,
"profile_image_file" => $_FILES['Filedata']['name'],
);
$apiHost = "https://tenant.thetenantsnet.co.uk/api/api/save_profile_image";
$response = $this->callRiseAPI2($apiData,$apiHost);
private function callRiseAPI2($apiData,$apiHost){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiHost);
curl_setopt($ch, CURLOPT_POST, count($apiData));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-Type: multipart/form-data');
$jsonData = curl_exec($ch);
if (false === $jsonData) {
throw new \Exception("Error: _makeOAuthCall() - cURL error: " . curl_error($ch));
}
curl_close($ch);
//return the API response
return json_decode($jsonData);
}
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.
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 ?
I use a funtion to download files trough a private API.
Everything goes fine to download small/medium files, but large files is impossible beacause it uses too much memory.
Here is my function:
protected function executeFile($method, $url, $params=array(), $as_user=null) {
$data_string = json_encode($params);
$method = strtoupper($method);
$ch = curl_init();
if($method == 'GET') {
$url = $this->options['api_url'].$url.'?';
$url .= $this->format_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($as_user) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Token: '.$this->token,
'As: '.$as_user
));
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Token: '.$this->token
));
}
$result_json = curl_exec($ch);
$curl_info = curl_getinfo($ch);
$return = array();
$return["result"] = $result_json;
$return["entete"] = $curl_info;
return $return;
}
How could i optimize this to download files to disk instead of memory ?
Thanks
use CURLOPT_FILE . It will ask for file pointer where download will be saved.
code will be like
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$fp = fopen("your_file", 'w+');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);
You can use CURLOPT_FILE, like this:
protected function executeFile($method, $url, $params=array(), $as_user=null) {
$data_string = json_encode($params);
$method = strtoupper($method);
$fp = fopen ('savefilepath', 'w+');
$ch = curl_init();
if($method == 'GET') {
$url = $this->options['api_url'].$url.'?';
$url .= $this->format_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
curl_setopt($ch, CURLOPT_URL, $this->options['api_url'].$url);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
....
curl_exec($ch);
fclose($fp);
.....
return $return;
}
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;
}
}
?>