CakePHP - sending POST requests in cakephp API and data handling - php

I have created a CakePHP app and after already set the routes.php files,i can send JSON requests,in order to use my app as an API. For testing,i have created a function which goes like this:
public function api() {
if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
$this->set('results',$result);
$this->set('_serialize',array('results'));
}
}
I have also created the exact same function with another name,which is meant to be used via a web form and that works correctly. BUT,this code,at this function here,when i POST data (i use Dev HTTP Client chrome extension),it returns the $results variable empty,like it does not receive what i send :/
I send the data as follows via the chrome extension i use:
data1='stuff1'&data2='stuff2'
and it returns me just
{
"results":""
}
(while the same code works perfectly when used without json).
Did i miss something?Does it seem to do something wrong? Please help me a bit around here..
ps:if you need more info,just tell me and i'll post it.
Thank you in advance!

The correct way to access that post would be
$this->request->data['data1'];
to verify what data is being sent do this:
public function api() {
//if($this->request->is('post')) {
$data1 = (string)$this->request->data['Model']['data1'];
$data2 = (string)$this->request->data['Model']['data2'];
//logic goes here,it does stuff and $result is the variable where the result of the login is saved
//$data1 and $data2 are used in the logic
$result = 'result';
//$this->set('results',$result);
$this->set('results',array('root'=>$this->request);
$this->set('_serialize',array('results'));
//}
}

Related

Laravel allow route to be accessible only from another route

I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.

Keep session with cURL in codeigniter php

I have a external API where I want to GET some data, and I want to keep session id through all the request until I log out. Using cURL lib in codeigniter I have the following flow (myacc and mypass are just placeholders):
public function getCURL() {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
}
This will output:
{"data":{"sid":"lH6WJCWMm5rkA14B0MPN570354"},"success":true}
I will have to keep that provided sid (session id) when making the next request:
http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2&timestamp=1480512959&preview=true&_sid="lH6WJCWMm5rkA14B0MPN570354"
See at the end sid="lH6WJCWMm5rkA14B0MPN570354".
And then log out and kill that sid.
After each login I would get a new sid that I have to use it to get a picture (with that URL) and then logout.
I think that saving and using cookies from a file in my case isn't needed, I think something like:
public function getCURL() {
echo $this->curl->simple_get('http://37.99.210.237:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
if ($this->form_validation->run()){
$data= array(
'sid'=> $this->input->post('sid'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
if(false == $this->CI->session->userdata('is_logged_in')) {
echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2&timestamp=1480512959&preview=true&_sid="sid"');
}
}
}
^^ That syntax is messed up, but how I can make it in a proper way or how it's the best way to keep session id on the request chain ?
if you want to keep sid for long session, for multiple request etc, you can save this json to some json file and clear content of file while logging out.
wrap your $sid getter to some other function.
function getSid()
{
//try to read from json
if(is_file('path/to/sid.json'){
$sid = json_decode(file_get_contents('path/to/sid.json', true));
if(!isset($sid['logout'])){
return $sid['data']['sid'];
}
}
$sid = $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
//check and save `$sid`
if(strlen($sid) > 20) {
file_put_contents('path/to/sid.json', $sid);
return json_decode($sid, true)['data']['sid'];
}
return false;
}
and update content of sid.json while logging out.
function logout()
{
file_put_contents('path/to/file', json_encode(['logout' => 'true']));
}
and call these methods.
for every request in one execution, it will use the same sid, and when you'll hit 'logout()' it will destroy the sid so that new generated and used on next execution.

Laravel 5.2.32: Session flash doesn't work with redirect

I have a controller which has a redirect function:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data);
}
This previousroute is handled by otherControllerMethod() like so:
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Unfortunately, Laravel forgets this session data. I've done this many times before and I have never seen if forget the session flash data after a single redirect. What is going on here? I have tried both adding and removing "web" middleware but nothing works. If anyone knows why this happens let me know.
use Session;
public function myControllerMethod()
{
$data = $this->blabla();
Session::set('data', $data);
return Redirect::to('previousroute')->with('data', $data);
}
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Try like this. Use the session and set the data in session and get it from where you want.
I have had the same Issue before. Basically I needed to call send function when redirecting using Redirect facade. So you need to change your myControllerMethod to:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data)->send();
}
As send() function of class Symfony\Component\HttpFoundation\Response calls the function sendContent() which sends the data when redirecting.
Hope this helps.
In myControllerMethod you are passing the data obj/var as a Request.
In otherControllerMethod you are requesting the Session data which is not set.
In order to put data to the session you should do:
Session::put('data','value')
and then it will be available with:
Session::get('data');

How to fetch user's First Name in php using Gmail Credentials as input?

I earlier used imap_open function in php to validate credentials of users from a form and give them login to my website.
Now I also want to print their name that can be fetched from Google Servers providing their credentials as input.
I want to Print something like "Hello $gmail->firstname to the website",
by providing the same user credentials from form as input to php file.
Is there anyway to do this without using Open ID API ?
My php function to authenticate was similar to this:-
function validate($username,$password) {
$username = strtolower($username);
$server="{imap.gmail.com:993/imap/ssl}";
$result=false;
$result = imap_open($server,$username,$password);
if($result) {
return 1;
}
else {
return 0;
}
}
try php's explode() function.
$string_array = explode("#",$string);
echo $string_array[0];
has ur answer.

calling ajax from within a php function having a switch ($this->method)

when creating an XMLrequest in a php file having a code which goes something like this... I am using a MVC ( model-view-controller structure ) and this is a controller php file..
Controller_Institute extends Controller_Default{
function register(){
try {
$this->requireLogin();
switch($this->method){
case 'GET':
$content = $this->render('institute_registration_confirm');
break;
case 'POST':
$result = mysql_query("SELECT * FROM password WHERE pass='".mysql_real_escape_string($_POST['pass'])."'");
$num=mysql_num_rows($result);
if($num==2)
{
$content = $this->render('institute_registration');
}
else
{
$content = $this- >render("message",array('msg'=>'Your password is incorrect'));
}
break;
}
$institute = R::dispense('institute');
$institute- >import($_POST,'name,latitude,state,longitude,address,phone,year,url');
$id = R::store($institute);
}
catch(exception $e){
//If there was an error anywhere, go to the error page.
$content = $this->render('error',array('exception'=>$e));
}
$page = $this->render('default',array('content'=>$content));
return $page;
}
i am sending the ajax request from within the function ... so when the ajax sends back the request , it gets caught in the switch case... and then the response text becomes the function return value replacing the actual text... any idea how to prevent the xml response from getting into the switch case...? the institute_registration is the view file and i am including that file in my framework and then triggering the ajax function from within that file to check whether the password ( to enable registration form ) is correct or not...
Given the limited information and pseudo-code, I recommend setting up a stand-alone page called say... "ajax.php" that is stand alone and doesn't base it's return value on the request method. The pages that use AJAX will need to either POST or GET from this page depending.
If you determine whether or not regular output vs AJAX output is returned via request method, then you are limiting yourself in 2 ways. The first is you will not be able to do 1 or the other on your web pages (GET vs POST) instead of both. Also, the second, when it comes to the AJAX, you will not be able to run GET & POST AJAX requests, and yes, you can do both with AJAX: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Categories