Issue with rest services - php

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

Related

Check if stream is on or off TWITCH API using PHP

The following ifalways return "Stream is Online!", even when "Stream is Offline!"
Could anyone point me the error?
<?php
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Client-id: clientidhere\r\n" . "Accept: application/vnd.twitchtv.v5+json\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_
contents('https://api.twitch.tv/kraken/streams/somestreaming', false, $context);
$json = json_decode($file);
if (($json->stream === "NULL") || ($json->stream === "null")) {
echo "Stream is Offline!";
} else {
echo "Stream is Online!";
}
?>
For me, I write as follows.
if (empty($http_response_header)){
echo "Stream is Offline!\n";
} else {
echo "Stream is Online!\n";
}
Note: $http_response_header is not empty when first request was succeeded then second request was failed, so you should need to empty $http_response_header before each requests.
$http_response_header = '';
file_get_contents(...);

PHP JSON error parsing the JSON document. The document may not be well-formed

This is my code:
if ($_SERVER ["REQUEST_METHOD"] === "GET") {
include_once('../database/dbSource.php');
$databaseSource = DataBaseSource::getInstance();
//Parse
$ini_array = parse_ini_file("../../pto/config.ini");
$user = $_GET['userSid'];
$username = $ini_array['ctsi_CIBMON_fid'];
$password = $ini_array['ctsi_CIBMON_pass'];
$ctsi_url = $ini_array['ctsi_url'] . $user . '&view=full';
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-Type: application/json\r\n" . "Accept: application/json\r\n" .
"Authorization: Basic " . base64_encode("$username:$password")
)
);
$context = stream_context_create($opts);
echo file_get_contents($ctsi_url, false, $context);
} else {
echo $_SERVER ["REQUEST_METHOD"];
}
I get the following error :
There was an error parsing the JSON document. The document may not be
well-formed.
I tried checking addiitonal spaces in code (which i removed) etc.
Also there is no issues with authorization.
Can't figure out what's the issue.
Please help.
Note: Also it used to work but stopped working without any change to code even. so Strange.
also the url that i am trying to access is https://xxx.xxx.net not http - does it matter?

How to get/set Header in Rest Server API?

i have a chriskacerguis Rest Server ,that listen for a client request as usually an API Server do.
base on client request i want to send/response some data to client in header only.
my questions are:
how do i access Client header first? then
how do i set Header in Rest Server?
This is how i send a request to REST SERVER:
function request_curl($url = NULL) {
$utc = time();
$post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
$header_data = array(
"Content-Type: application/json",
"Accept: application/json",
"X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
"X-UTC:" . $utc,
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header_data,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) {
die(curl_error($ch));
}
curl_close($ch);
echo '<pre>';
print_r($answer);
echo '</pre>';
}
Below is my REST SERVER function that listen request and will response a header:
public function clientRequest_post() {
// Getting Post Data
$entityBody = file_get_contents('php://input', 'r');
$this->response($entityBody,200);
//getting header data ,no idea
}
May be try php function getallheaders() which will fetch all the header data for you. If you want to convert it into array, use foreach.
So this will get you the header data and will convert it into array
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
Now if you want to get body and convert it into array as well
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
The final function will look something like this...
public function clientRequest_post() {
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
$this->response($entityBody, 200);
}
Btw, I assume $this->response($entityBody,200); will generate the response for you. Best of luck with it

Restful API for CakePHP 2

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>';

Twitter Oauth via PHP WITHOUT cURL

My server does not support cURL.
I want to update my status via php.
How to do that without cURL?
Again: WITHOUT CURL!
Here’s how you can tweet without using cURL with PHP.
We have two options-
With stream context
Php function stream_context_create has the magic. It creates and returns a stream context with any options passed.
<?php
set_time_limit(0);
$username = 'username';
$password= 'WHATEVER';
$message='YOUR NEW STATUS';
function tweet($message, $username, $password)
{
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)).
"Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(array('status' => $message)),
'timeout' => 5,
),
));
$ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);
return false !== $ret;
}
echo tweet($message, $username, $password);
?>
With socket programing
PHP has a very capable socket programming API. These socket functions include almost everything you need for socket-based client-server communication over TCP/IP. fsockopen opens Internet or Unix domain socket connection.
<?php
$username = 'username';
$password= 'WHATEVER';
$message='YOUR NEW STATUS';
$out="POST http://twitter.com/statuses/update.json HTTP/1.1\r\n"
."Host: twitter.com\r\n"
."Authorization: Basic ".base64_encode ("$username:$password")."\r\n"
."Content-type: application/x-www-form-urlencoded\r\n"
."Content-length: ".strlen ("status=$message")."\r\n"
."Connection: Close\r\n\r\n"
."status=$msg";
$fp = fsockopen ('twitter.com', 80);
fwrite ($fp, $out);
fclose ($fp);
?>
Taken from here: http://www.motyar.info/2010/02/update-twitter-status-with-php-nocurl.html
Hope htis helps.
If you need any more help let me know as i am a php programmer myself.
thanks
PK
<?php
/*
* using file_get_contents
*/
$key = '';
$secret = '';
$api_endpoint = 'https://api.twitter.com/1.1/search/tweets.json?q=news'; // endpoint must support "Application-only authentication"
// request token
$basic_credentials = base64_encode($key.':'.$secret);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Basic '.$basic_credentials."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials'
)
);
$context = stream_context_create($opts);
// send request
$pre_token = file_get_contents('https://api.twitter.com/oauth2/token', false, $context);
$token = json_decode($pre_token, true);
if (isset($token["token_type"]) && $token["token_type"] == "bearer"){
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Authorization: Bearer '.$token["access_token"]
)
);
$context = stream_context_create($opts);
$data = file_get_contents($api_endpoint, false, $context);
print $data;
}
?>
You can do that using the oauth pecl extension. See here for details.
EDIT: you need to install the pecl extension

Categories