What mistake I'm making in calling an API written in Slim? - php

I'm using Slim framework to access the functions from existing PHPFox website. I'm just a newbie to Slim framework so truing to learn it.
I've included the necessary file for this. But the issue I'm facing is I'm always getting "404 Page Not Found" error upon making request. Even I tried to print the message "Object Created" after creation of object, it got printed that means till this point there is no error. When I try to get inside the function by echoing some message I got 404 error.
Can someone please help me in correcting the mistake I'm making in my code?
Following is my code (login_ws.php):
<?php
require 'Slim/Slim.php';
require('config.php');
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
//Object created
$application->map (
'/login/:login/:password/:divice_type',
function()
{ echo "Ina funcionality"; die;
global $application;
if($application->request->isGet()) {
$login = $application->request->get('login');
$password = $application->request->get('password');
$divice_type = $application->request->get('divice_type');
/*$divice_token = $application->request->get('divice_token');*/
}
if($application->request->isPost()) {
$login = $application->request->post('login');
$password = $application->request->post('password');
$divice_type = $application->request->post('divice_type');
/*$divice_token = $application->request->post('divice_token');*/
}
list($bLogged, $aUser) = Phpfox::getService('user.auth')->login($login, $password);
if($aUser['user_image']) {
$aUser['user_image'] = Phpfox::getParam('core.url_user').$aUser['user_image'];
} else {
$aUser['user_image'] = '';
}
if((!empty($aUser)) && ($bLogged>0)) {
$msg='Login succesfully';
Phpfox::getService('user.auth')->setUserId($aUser['user_id']);
$appKey = Phpfox::getService('apps')->getKey('3');
$test = doPost("http://localhost/token.php?key=".$appKey);
$arrayToken = json_decode($test);
$aUser['token'] = $arrayToken->token;
$aUser['key'] = $appKey;
} else {
$msg='Login Failed';
$aUser[]=$login;
$aUser[]=$password;
}
$result=array('status'=>$bLogged ? 'true' : 'false','data'=>$aUser,'msg'=>$msg);
header("Content-Type: application/json");
echo json_encode($result);
}
)->via('GET','POST');
//Purpose of via() : The function will be invoked when there is a match for the URI whether the request is using HTTP GET or HTTP POST method.
$application->run();
function doPost($aParams) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $aParams);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
The request I'm making through browser's URL is as follows:
http://localhost/webservice/login_ws.php/login?login=admin#gmail.com&password=admin123&divice_type=iphone
Please help me in correcting the mistake I'm making. Also if you find I'm doing anything in wrong way which is not standard for Slim framework please correct me. I'd be more than happy for it.
Thanks.

Related

php curl requesting twice

I have a limit of 25 requests/min from PUBGs official API. For some reason instead of it requesting twice for each search its using up 4 requests. I can't figure out why. I have checked that the code isn't running twice. Only once, but still it's requesting 4 times.
UPDATE:
I tried making a separate page and apparently there is a bug somewhere calling my function twice. Still don't know why but I'm now 99% sure it's not the function itself.
Code For My Request
function getProfile($profileName, $region, $seasonDate){
// Just check if there is an acctual user
if($profileName === null){
$data->error = "Player Not Found";
$data->noUser = true;
return $data;
}else{
$season = "division.bro.official.".$seasonDate;
/*
Get The UserID
*/
$ch = curl_init("https://api.pubg.com/shards/$region/players?filter[playerNames]=$profileName");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer APIKEY',
'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$rawData = json_decode(curl_exec($ch), true);
$data->playerId = $rawData["data"][0]["id"];
curl_close($ch);
// Testing if user exists
if($rawData["errors"][0]["title"] === "Not Found"){
$data->noUser = true;
$data->error = "Player Not Found";
return $data;
}else{
/*
Get The acctual stats
*/
$ch = curl_init("https://api.pubg.com/shards/$region/players/$data->playerId/seasons/$season");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer APIKEY',
'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data->playerDataJSON = curl_exec($ch);
$data->playerData = json_decode($data->playerDataJSON, true);
curl_close($ch);
return $data;
}
}
}
This is how it's getting called
if (isset($_POST['search-username'])) {
$username = $_POST['search-username'];
header("Location: /profile/$username/pc-na/2018-01/overall/tpp");
die();
}
In The actual profile php
$data = getProfile($page_parts[1], $page_parts[2], $page_parts[3]);
absolutely sure it's only called once? set a lock on it. change it to
function getProfile($profileName, $region, $seasonDate){
static $once=true;
if($once!==true){
throw new \LogicException("tried to run getProfile() twice!");
}
$once=false;
Shortly after I figure out it's not the function I realized that the culprit was an empty script I was calling. I knew this script created an error which I didn't really care about since it was empty and I had no idea why it was creating the error. For some obscure reason this script created the error. I'll just make a lesson out of it to always fix the smallest errors.
I've also been seeing this behavior - a script with a single curl_exec() request gets called twice.
The strange thing is this was only happening when running on localhost (under a wampp installation) but when run from any other webserver was fine and it is just called once.
I never managed to debug it completely but it seems to be an issue with the local server so test elsewhere if you are seeing this.

Is it possible execute a function in Prestashop via hooks without creating a module?

I have created this test function (lets call it ABtest.php) to send a test message:
$host = "http://localhost:8080";
$id = "123";
$email = "mine.mail#gmail.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "mine.mail:mypassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, TRUE);
function send($host,$id,$email,$ch){
curl_setopt($ch, CURLOPT_URL, $host . "/c/" . $id . "/your ID/");
curl_setopt($ch, CURLOPT_POSTFIELDS, "to=" . $email . "&subject=Your ID ");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$output = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200 && curl_getinfo($ch, CURLINFO_HTTP_CODE) != 201) {
printf("An error occured (HTTP %d): %sn", curl_getinfo($ch, CURLINFO_HTTP_CODE), $output);
} else {
printf("Success");
}
}
I would like to place this code into my hook hookValidateOrder($params) like this:
public function hookValidateOrder($params)
{
$id = $params['cart']->id;
$host = "http://localhost:8080";
$email = "mine.mail#gmail.com";
// + the rest of my PHP function - see the 1st code block above
}
The problem is that I donĀ“t really know where to place my code. As You can see I am not creating a module, I just want to execute my PHP function via hookValidateOrder($params) hook.
Is that possible and where do I place it?
I don't think so. Not in the proper way.
But you can create an override, in the overrides folder for PaymentModule.php:
abstract class PaymentModule extends PaymentModuleCore
{
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
{
// do what you need before
parent::validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method, $message, $extra_vars, $currency_special, $dont_touch_amount, $secure_key, $shop);
// do what you need after
}
}
You can also override the any module to do it, or the hook exec and check if it's trying to execute the hookValidateOrder then you place your code.
If you do create an override, don't forget to delete (or rename) the file cache/class_index.php after, to index you new override.

How to test logstash with PHP script

I just have installed logstash, configured its config file with input, filter and output and finally have run it. Is it possible to test if logstash pushes log data by writing some PHP script? Can someone provide me some php script that can catch log data, sending from logstash?
Run the following to get the list of logs in your elasticsearch index :
$date = date("Y.m.d");
$host = "127.0.0.1";
$port = "9200";
$index = "logstash-".$date;
$type = "*";
$log = array();
$query = '{"query":{"match_all":{}}}';
$curl = curl_init();
if ($curl) {
curl_setopt($curl,CURLOPT_URL, $host."/".$index."/".$type."/_search");
curl_setopt($curl, CURLOPT_PORT, $port);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
if (curl_errno($curl)) {
echo curl_error($curl); //error
}
curl_close($curl);
if (!$result) {
//error
}
$arr=(json_decode($result, true));
$logs = $arr['hits']['hits'];
// If any logs were found
if (count($logs)>0) {
foreach ($logs as $q) {
// load the data in the $data array
$log[] = $q["_source"];
echo "<pre>";
print_r($log);
echo "</pre>";
}
}
}
?>
Cheers.
Do you have use Elasticsearch to store the log data? After you have store the logs in elasticsearch, you can use restful api to get the logs by php.
You must install Elasticsearch PHP client to communicate with elasticsearch server.

Restservice with curl simpleget not working

I'm trying to use my webservice by curl:
public function getImages($time) {
$url = $this->rest_url['employees'] . "?action=getAllNewPhotos&accessKey=" . $this->rest_key['employees'] . "&lastcheck=" . $time;
$data = $this->CI->curl->simple_get($url);
if ($data) {
return json_decode($data);
} else {
return null;
}
}
But it keeps giving me the following error:
Fatal error: Call to a member function simple_get() on a non-object
Why is that?
Also if I add curl in my autoload it says:
Unable to load the requested class: curl
However if I run my code by following code, there is no problem:
$url = $this->rest_url['employees'] . "?action=getAllNewPhotos&accessKey=" . $this->rest_key['employees'] . "&lastcheck=" . $time;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
if ($data) {
return json_decode($data);
} else {
return null;
}
I'm just curious why my first approach is not working!
If you need more clarification, please let me knwo!
Thanks
You seem to be mixing a few things.
If you want to load this as a Codeigniter library, you need to first create it as one. Steps are found in the User Guide. This will go in your libraries directory.
simple_get() should then be a function on your class library called "curl". However, I would probably use a different name to avoid naming clashes

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories