I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';
Related
The error I get:
Warning: file_get_contents(https://api.imgur.com/3/image): failed to open stream: HTTP request failed! HTTP/1.1 403 Permission Denied in
C:\xampp\htdocs\sn0\classes\Image.php on line 22
Notice: Trying to get property of non-object in
C:\xampp\htdocs\sn0\classes\Image.php on line 25
Notice: Trying to get property of non-object in
C:\xampp\htdocs\sn0\classes\Image.php on line 25
Here's my Image.php file:
<?php
class Image {
public static function uploadImage($formname, $query, $params) {
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
$options = array('http'=>array(
'method'=>"POST",
'header'=>"Authorization: Bearer ###\n".
"Content-Type: application/x-www-form-urlencoded",
'content'=>$image
));
$context = stream_context_create($options);
$imgurURL = "https://api.imgur.com/3/image";
if ($_FILES[$formname]['size'] > 10240000) {
die('Image too big, must be 10MB or less!');
}
$response = file_get_contents($imgurURL, false, $context);
$response = json_decode($response);
$preparams = array($formname=>$response->data->link);
$params = $preparams + $params;
DB::query($query, $params);
}
}
?>
You making bad request.
At the beginning you need to generate your Client ID (more info # https://api.imgur.com/#registerapp)
To do this go to https://api.imgur.com/oauth2/addclient
and
Select Anonymous usage without user authorization option as Authorization Type.
Use Authorization: Client-ID not Bearer, you can keep file_get_contents (so - then you need change only authorization header) but CURL will be better for this.
Example with CURL:
<?php
class Image
{
public static function uploadImage($formname, $query, $params)
{
$client_id = 'YOUR CLIENT ID';
$image = base64_encode(file_get_contents($_FILES[$formname]['tmp_name']));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.imgur.com/3/image.json',
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => array(
'Authorization: Client-ID ' . $client_id
) ,
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => array(
'image' => $image
)
));
$out = curl_exec($curl);
curl_close($curl);
$response = json_decode($out);
$preparams = array(
$formname => $response->data->link
);
$params = $preparams + $params;
DB::query($query, $params);
}
}
file_get_contents() is used for GET requests. You need to use CURL in PHP in order to make a POST request from a server to another.
This question is market as answered in this thread:
How to POST an XML file using cURL on php?
But that answer wasn't really the correct answer in my opinion since it just show how to send XML code with cURL. I need to send an XML file.
Basically, I need this C# code to be converted to PHP:
public Guid? UploadXmlFile()
{
var fileUploadClient = new WebClient();
fileUploadClient.Headers.Add("Content-Type", "application/xml");
fileUploadClient.Headers.Add("Authorization", "api " + ApiKey);
var rawResponse = fileUploadClient.UploadFile(Url, FilePath);
var stringResponse = Encoding.ASCII.GetString(rawResponse);
var jsonResponse = JObject.Parse(stringResponse);
if (jsonResponse != null)
{
var importFileId = jsonResponse.GetValue("ImportId");
if (importFileId != null)
{
return new Guid(importFileId.ToString());
}
}
return null;
}
I have tried in several ways and this is my latest try.
The cURL call:
/**
* CDON API Call
*
*/
function cdon_api($way, $method, $postfields=false, $contenttype=false)
{
global $api_key;
$contenttype = (!$contenttype) ? 'application/x-www-form-urlencoded' : $contenttype;
$curlOpts = array(
CURLOPT_URL => 'https://admin.marketplace.cdon.com/api/'.$method,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => array('Authorization: api '.$api_key, 'Content-type: '.$contenttype, 'Accept: application/xml')
);
if ($way == 'post')
{
$curlOpts[CURLOPT_POST] = TRUE;
}
elseif ($way == 'put')
{
$curlOpts[CURLOPT_PUT] = TRUE;
}
if ($postfields !== false)
{
$curlOpts[CURLOPT_POSTFIELDS] = $postfields;
}
# make the call
$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
The File Export:
/**
* Export products
*
*/
function cdon_export()
{
global $api_key;
$upload_dir = wp_upload_dir();
$filepath = $upload_dir['basedir'] . '/cdon-feed.xml';
$response = cdon_api('post', 'importfile', array('uploaded_file' => '#/'.realpath($filepath).';type=text/xml'), 'multipart/form-data');
echo '<br>Response 1: <pre>'.print_r(json_decode($response), true).'</pre><br>';
$data = json_decode($response, true);
if (!empty($data['ImportId']))
{
$response = cdon_api('put', 'importfile?importFileId='.$data['ImportId'], false, 'text/xml');
echo 'Response 2: <pre>'.print_r(json_decode($response), true).'</pre><br>';
$data = json_decode($response, true);
}
}
But the output I get is this:
Response 1:
stdClass Object
(
[Message] => The request does not contain a valid media type.
)
I have experimented around with different types at the different places, application/xml, multipart/form-data and text/xml, but nothing works.
How do I do to make it work? How do I manage to send the XML file with cURL?
to me, it looks like the C# code just does the equivalent of
function UploadXmlFile(): ?string {
$ch = curl_init ( $url );
curl_setopt_array ( $ch, array (
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array (
"Content-Type: application/xml",
"Authorization: api " . $ApiKey
),
CURLOPT_POSTFIELDS => file_get_contents ( $filepath ),
CURLOPT_RETURNTRANSFER => true
) );
$jsonResponse = json_decode ( ($response = curl_exec ( $ch )) );
curl_close ( $ch );
return $jsonResponse->importId ?? NULL;
}
but at least 1 difference, your PHP code adds the header 'Accept: application/xml', your C# code does not
I'm creating a function to untilize NameCheap's API for registering domain names. The registration process worked out smoothly, now I'm looking to set the proper DNS Hosts.
When I create a pure POST request with something like POSTMAN this works fine and returns the expected XML response. However when I try to pass the data through PHP's CURL functions it breaks. I've narrowed the problem the the '#' symbol that needs to be passed to the DNS Host. If i put anything else there the request goes through. I've tried to url_encode the symbol but the API does not accept that.
Any suggestions?
public function setDNSHost($name, $server){
list($domain,$tld) = explode('.',$name,2);
$request = $this->request_URL;
$curl = curl_init();
$args['ApiUser'] = $this->API_User;
$args['ApiKey'] = $this->API_Key;
$args['UserName'] = $this->API_User;
$args['Command'] = 'namecheap.domains.dns.setHosts';
$args['ClientIP'] = $this->Client_IP;
$args['SLD'] = $domain;
$args['TLD'] = $tld;
$args['HostName1'] = utf8_encode('#');
$args['RecordType1'] = 'A';
$args['Address1'] = $server;
$args['HostName2'] = 'www';
$args['RecordType2'] = 'CNAME';
$args['Address2'] = $name;
$args['HostName3'] = '*';
$args['RecordType3'] = 'CNAME';
$args['Address3'] = $name;
curl_setopt_array($curl, array(
CURLOPT_URL => $request,
CURLOPT_USERAGENT => 'API',
// CURLOPT_FAILONERROR => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $args,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec($curl);
curl_close($curl);
// $oXML = new SimpleXMLElement($response);
return $response;
}
Some caracters are not allowed to be in the string. To avoid such problems you could use http_build_query on your data before you use the curl function.
I am facing one issue while i am calling rest service using file_get_contents
its working fine when response is success but its giving blank result in case of failure or error response. while when I am checking it using rest client its giving me correct response for both case whether its success or failure.
can anyone please help? below is the source code which i have written.
<?php
$postdata = array(
'email' => $email,
'password' => $password
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $headers = array(
'Accept: application/json',
'Content-Type: application/json'
)
//'content' => $postdata
)
);
$context = stream_context_create($opts);
//echo "<pre>"; print_r($context); exit;
$url = WS_URL . "issavvy-api/account/login?" . http_build_query($postdata);
$result = file_get_contents($url, false, $context);
echo "<pre>";
print_r(json_decode($result));
exit;
?>
If you wanna stick with file_get_contents use $http_response_header and parse it
You can use this
function httpStatusCode($headers){
$match = null;
$pattern = "!(?P<version>HTTP/\d+\.\d+) (?P<code>\d+) (?P<status>.*)!";
foreach($headers as $header){
if(preg_match($pattern, $header, $match)){
return $match['code'];
}
}
return null;
}
To check if request was successful run
$success = (200 == httpStatusCode($http_response_header));
https://eval.in/145906
I'm trying to use curl instead of the http request 2 pear module in PHP to query the plivo api. They have an existing library for easily making calls to their API but it uses a pear module called http request2. I don't really know how to install a pear module on a server so I thought of just rewriting some parts of their library to just use curl.
Here's the part of their code that I specifically want to modify:
function __construct($auth_id, $auth_token, $url="https://api.plivo.com", $version="v1") {
if ((!isset($auth_id)) || (!$auth_id)) {
throw new PlivoError("no auth_id");
}
if ((!isset($auth_token)) || (!$auth_token)) {
throw new PlivoError("no auth_token");
}
$this->version = $version;
$this->api = $url."/".$this->version."/Account/".$auth_id;
$this->auth_id = $auth_id;
$this->auth_token = $auth_token;
}
private function request($method, $path, $params=array()) {
$url = $this->api.rtrim($path, '/').'/';
if (!strcmp($method, "POST")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST);
$req->setHeader('Content-type: application/json');
if ($params) {
$req->setBody(json_encode($params));
}
} else if (!strcmp($method, "GET")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET);
$url = $req->getUrl();
$url->setQueryVariables($params);
} else if (!strcmp($method, "DELETE")) {
$req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE);
$url = $req->getUrl();
$url->setQueryVariables($params);
}
$req->setAdapter('curl');
$req->setConfig(array(
'timeout' => 30,
'ssl_verify_peer' => FALSE,
));
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
$req->setHeader(array(
'Connection' => 'close',
'User-Agent' => 'PHPPlivo',
));
$r = $req->send();
$status = $r->getStatus();
$body = $r->getbody();
$response = json_decode($body, true);
return array("status" => $status, "response" => $response);
}
public function get_account($params=array()) {
return $this->request('GET', '', $params);
}
And here's the code that I have so far:
<?php
$curl = curl_init();
$curl_options = array(
CURLOPT_URL => 'https://api.plivo.com/v1/Account/',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_USERPWD => 'auth_id:auth_token',
CURLOPT_HTTPHEADER => array("Connection: close", "User-Agent: PHPPlivo"),
CURLOPT_TIMEOUT => 30
);
curl_setopt_array($curl, $curl_options);
$response = curl_exec($curl);
curl_close($curl);
?>
I don't really know what's going on behind the scenes but this specific code is telling me that its using basic authentication using the values for the auth id and auth token:
$req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC);
So I also set it using curl:
CURLOPT_USERPWD => 'auth_id:auth_token',
I'm pretty much stuck. All I get as a respose is the following:
{
"error": "not found"
}
It doesn't really make much sense into what I have missed or done wrong. Please help. Thank you in advance!
Below are the things you need to handle to sync your new code with old one:
If you are using GET method
CURLOPT_URL => 'https://api.plivo.com/v1/Account/'.http_build_query($params),
CURLOPT_HTTPHEADER => array("User-Agent: PHPPlivo"),
If you are using POST method
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => array("Content-type: application/json", "User-Agent: PHPPlivo"),
Yea... The PEAR dependency is definitely overkill for Plivo's wrapper. So that was one of the first modifications I made to the code.
Check out:
https://github.com/ashbeats/Plivo-Curl-Based-Wrapper/
Only difference is the RestAPI::request() method.