I'm using PHP 5.3, and trying to develop a simple web service that gets some parameters with POST method and has a response.
function start(){
getAndValidateParams();
global $response;
echo json_encode($response);
}
function getAndValidateParams(){
// token (mandatory)
if(isset($_POST[PARAM_TOKEN])){
echo 'got your token';
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
}
I'm trying to test that with Postman:
The problems:
1. About the Xdebug HTML I saw the following question, If I turn the var_dump off, will it disable usage of var_dump() inside my php code? (I want to be able use it for debugging but not seeing that in the response).
2.Also I have a problem to pass the parameter 'token', I don't see it in getAndValidateParams().
Any help will be appreciated.
I have used your function to just get insight in this and for tesing you can use also there is Advanced REST client in chrome similar to postMAN that you are using --
use the below lines to debug this --
function start(){
$response = getAndValidateParams();
return json_encode($response);
}
// calling function ends here
// statrt another function that is being called
function getAndValidateParams(){
// token (mandatory)
// print_r($_POST);die; // just for debug purpose
if(isset($_POST[PARAM_TOKEN])){
$response[ERROR_CODE] = 0;
$response[DESCRIPTION] = "Success";
$response[DEtail] = $yourdetailarr; // array of data that you want to retuen
}else{
$response[ERROR_CODE] = ERR2_INVALID_TOKEN;
$response[DESCRIPTION] = CODE2_DESC;
}
return $response;
}
/// ends here
check the response here by calling start function .
Related
I have a function developed by PHP that at the moment all I want it to do is to return the value of the variable $_POST['token']
I tried:
public function actionGetuserbytoken() {
$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['token'];
return $id;
}
Or I also just tried:
public function actionGetuserbytoken() {
return $_POST['token'];
}
I tried doing the POST with Insomnia to check what is going on:
I feel this is a very absurd question but I can't understand why I can't get the value of the POST in either of the two ways.
The php://input stream can only be read once per request. Yii is likely reading the payload before you can, which means that the body is empty when you read the data.
Instead of using php://input, try the following:
$data = json_decode(Yii::app()->request->getRawBody(), true);
This May sound like a silly question but, I have a method that normally returns a JSON response to the client side. But now I need the same method within the class to prevent DRY. Something like:
public function deleteChild($id){
// delete the element with given id ...
if($success){
return response()->json(['success'=>'successfully deleted'], 200);
}else{
return response()->json(['error'=>'could not be deleted'], 422);
}
}
This method is already used by the client side. But now I have another one that needs this method as well. Something like:
public function deleteMaster($id){
$master = Master::find($id);
foreach($child as $master->children){
$child_json_response = $this->deleteChild($child->id);
$response_data = $child_json_response->getData();
if($response_data->error){
// handle child error response
// ...
}
// delete master itself
}
}
Here I can extract the response data with getData() and process it.
Is this the right way to use a sibling function that returns a JSON response (actually made for client-side) or should I create another method that returns direct results serving server-side only?
You should use a Response macro
Into a service provider's boot, add this:
\Illuminate\Http\Response::macro('deleteJson', function ($success) {
return $success
? $this->json(['success'=>'successfully deleted'], 200)
: $this->json(['error'=>'could not be deleted'], 422);
}
public function deleteChild($id){
// delete element with given id ...
return response()->deleteJson($success);
}
I'm using Zurmo and trying to create a new account using REST API. I followed this documentation precisely: http://zurmo.org/wiki/rest-api-specification-accounts to pass the required parameters as json array.
This is my php code:
public function actionCreateOrUpdate()
{
$params=$_POST;
$modelClassName=$this->getModelName();
foreach ($params as $param)
{
if (!isset($param))
{
$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);
}
$r=$this->GetParam($param);
$res= array('status' => 'SUCCESS', 'data' => array($r));
print_r(json_encode($res,true));
}
}
function GetParam ($param){
$modelClassName=$this->getModelName();
if (isset($param['mobile_id'] ) && !$param['mobile_id']=='' &&!$param['mobile_id']==null)
{ $id=$param['mobile_id'];
$params=array();
foreach ($param as $k => $v) {
if(!($k=='mobile_id')) {
$params[$k] = $v;}
}
if ($params=null){$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);}
$tableName = $modelClassName::getTableName();
$beans = ZurmoRedBean::find($tableName, "mobile_id = '$id'");
if (count($beans) > 0)
{
$result = $this->processUpdate($id, $params);
}else{
$result = $this->processCreate($params,$id);
}
}
return $result;
}
The problem is that the $_POST method is returning an empty array. While debugging I tried to use print_r($_POST) and it also returned an empty array. I also tried to pass parameters as plain text and got the same result. I tried $_GET method and it worked. I think the problem is in the $_POST method, maybe I need to change something in my .php files. Any ideas please?
You should first hit the api with static data, to check if it works fine, then try to integrate php within that static data. You will need to read the documentation for which action accepts which format, and which method is supported(GET OR POST). Then try die(); , before sending if the array formed is as per the documentation.
I had similar issue when creating Account using REST API from java client. The problem was I did not send the proper POST request.
Another symptom also was on server side print_r(file_get_contents("php://input"),true); php code returned the correct request data.
Specifically the root cause was:
The Content-Type HTTP header was not "application/x-www-form-urlencoded"
The value field value in POST request was not properly encoded ( I used java.net.URLEncoder.encode method to overcome this)
After fixing these it worked.
I am using xmlprc server in codeignter for web services . the flow of my application is that i need to pass parameters to the xmlrpc server method which then should invoke another controller class method which would set the parameters in a js function and that js method is invoked concurrently .
The problem i am facing is in calling the controller class method from the xmlrpc server method and getting the response to the server parent method which could then be fetched using xmlhttprequest.
my xmlrpc server method is:
function update_p($request) {
$parameters = $request->output_parameters();
$this->session->set_userdata(array("portfolio" =>$parameters['0']["portfolio"]));
$this->session->set_userdata(array("filter" =>$parameters['0']["filter"]));
$url = base_url("ControllerClass/update_p?".$parameters['0']["portfolio"].'&'.$parameters['0']["filter"]);
header("Location: $url");
$xml_rpc_rows=array("portfolio"=>$parameters['0']["portfolio"],"filter"=>$parameters['0']["filter"]);
$response = array(
$xml_rpc_rows,
'struct');
$this->xmlrpc->send_response($response);
}
Controller Class method:
public function update_p() {
$loginid = $this->session->userdata('loginid');
if(!isset($loginid)){
die;
}
error_reporting(E_ERROR);
if (time()>$this->session->userdata('expire')) { redirect("/dashboard/logout?expired=Y","location",401); die; }
$out='';
$request="USER ".$loginid.($this->session->userdata('isMobile')?"#mobile":"")."\n";
if(isset($_GET["portfolio"])) {
$portfolio=trim($_GET["portfolio"]);
$request.='ECHO "LISTP":'."\nLISTP0 #".$portfolio;
if(isset($_GET["filter"])) {
$filter=trim($_GET["filter"]);
$request.=" -".$filter;
}
if(isset($_GET["sort"])) {
$sort=trim($_GET["sort"]);
if ($sort>=1024) $request.=" -s".($sort&1023);
else $request.=" -S".$sort;
}
$ph = isset($_GET["first"]);
if ($ph) {
$this->load->model('Model');
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','listp');
$request.=" ".$resultArray[0]['listp'];
}
$request.="\nECHO ,\n";
if(isset($_GET["watch"])) {
$portfolio=trim($_GET["watch"]);
if ($ph)
$resultArray = $this->Model->getData($this->session->userdata('loginid'),$this->session->userdata('isMobile')?'mobile':'default','watch');
$request.='ECHO "watchl":'."\nLISTP1 #".$portfolio." -WL ".($ph?$resultArray[0]['watch']:"")."\n";
$request.='ECHO ,"watchs":'."\nLISTP1 #".$portfolio." -WS\nECHO ,\n";
}
}
$request.="RISk\nECHO ,\nPnL\n";
if ($result=$this->getData($request."BYE\n")) {
if (result!='') $out=$result."\n";
}
ob_start('ob_gzhandler');
echo "{".$out."}";
ob_end_flush();
}
I can not figure out how to get the controller method result in the server method anyone who can shed some light on this would be much appreciated .
Thankyou.
Your controller method is expecting to output the result as an echo statement, which goes to the browser, rather than to return it in a variable. This means your server function is having to try to capture the output of that controller method. That setup is much more awkward and prone to error.
Unless you also need to access your update_p method directly from a browser you should change your Controller to simply return the output which really means this controller is more of a library and should probably go in the libraries folder. You will need to change your controller code a bit so that instead of grabbing the parameters from $_GET you are getting them as arguments, which in CodeIgniter is what you should be doing anyway.
So from the end of update_p just do this instead of your echo:
return "{".$out."}";
Then in your xmlrpc server do this:
$controller = new ControllerClass();
$result = $controller->update_p($parameters['0']["portfolio"], $parameters['0']["filter"]);
Then do whatever you want with your $result.
Im trying to use the GiantBomb api to query video games, and currently when I enter the URL into a browser, it works just fine. The Json data shows up.
Heres an example url..
http://www.giantbomb.com/api/search/?api_key=83611ac10d0dfghfgh157177ecb92b0a5a2350c59a5de4&query=Mortal+Kombat&format=json
But when I try to use my php wrapper that Im just starting to build, it returns html??
Heres the start of my wrapper code....(very amateur for now)
You'll notice in the 'request' method, Ive commented out the return for json_decode($url), because when I uncomment it, the page throws a 500 error??? So I wanted to see what happends when I just echo it. And it echos an html page. Surely it should just echo what is shown, when you just enter that url into the browser, no?
However...if I replace the url with say a GoogleMap url, it echoes out Json data just fine, without using json_decode. Any ideas as to wahts going on here????
class GiantBombApi {
public $api_key;
public $base_url;
public $format;
function __construct() {
$this->format="&format=json";
$this->api_key = "83611ac10d0d157177ecb92b0a5a2350c59a5de4";
$this->search_url = "http://www.giantbomb.com/api/search/?api_key=".$this- >api_key."&query=";
}
public function search($query){
$query = urlencode($query);
$url = $this->search_url.$query.$this->format;
return $this->request($url);
}
public function request($url) {
$response = file_get_contents($url);
echo $response;
//return json_decode($response, true);
}
}
//TESTING SECTION
$games = new GiantBombApi;
$query = $_GET['search'];
echo $games->search($query);
I ran a few requests through Postman and it seems that the api looks at the mime-type as well as the query string. So try setting a header of "format" to "json".