Data range in URL Routes Codeigniter - php

I have an API that's working fine without this data range in URL, but now I need to set to better search, as this example, after /orders.
E.g.: http://localhost/ws/v1/orders?fromDate=2019-01-01&toDate=2019-12-31
Controller:
public function getOrders_get($id = 0){
header("Access-Control-Allow-Origin: *");
// Load Authorization Token Library
$this->load->library('Authorization_Token');
/**
* User Token Validation
*/
$is_valid_token = $this->authorization_token->validateToken();
if (!empty($is_valid_token) AND $is_valid_token['status'] === TRUE)
{
if (empty($id)){
$data = $this->db->get("order_view")->result();
}else{
$data = $this->db->get_where("order_view", ['id' => $id])->row_array();
}
$this->response($data, REST_Controller::HTTP_OK);
} else {
$this->response(['status' => FALSE, 'message' => $is_valid_token['message'] ], REST_Controller::HTTP_NOT_FOUND);
}
}

You can add a between to you sql.
$from_date = $_GET['fromDate'];
$to_date = $_GET['toDate'];
...
$this->db->where("date between $from_date and $to_date");

Related

How to pass calculated/final value of one function to other functions in a controller of Codeigniter application

Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

Route with $id or all data in Codeigniter

I want to get all my data or select with by id, but something is wrong. When I try with route, not work. If i try without route, the select by ID work, and without id have "Missing argument..."
mysite.com/ws/v1/article - Return all my data (ok) but also a "Missing argument for Articles".
mysite.com/ws/v1/article/6 (6 = id example) Return "The page is not found".
Routes
$route['ws/v1/article'] = "api/articles/getArticle";
Controller
public function getArticle_get($id)
{
header("Access-Control-Allow-Origin: *");
// Load Authorization Token Library
$this->load->library('Authorization_Token');
/**
* User Token Validation
*/
$is_valid_token = $this->authorization_token->validateToken();
if (!empty($is_valid_token) AND $is_valid_token['status'] === TRUE)
{
if (empty($id)){
$data = $this->db->get("ga845_clientes")->result();
}else{
$data = $this->db->get_where("ga845_clientes", ['id' => $id])->row_array();
}
$this->response($data, REST_Controller::HTTP_OK);
} else {
$this->response(['status' => FALSE, 'message' => $is_valid_token['message'] ], REST_Controller::HTTP_NOT_FOUND);
}
}
This is how you pass the parameters in your api.
mysite.com/ws/v1/article/$6
To make your parameter optional,
$route['ws/v1/article/?(:id)?'] = "api/articles/getArticle/$1";

Laravel 5 Redirect from a sub-method

I'm using Socialite to get user information from facebook. All is going well but my redirect isn't working
Sub-routes
I read that it's not possible to do a redirect from a submethod, or
any method that's not in your routes.
But how else can i redirect the user after I logged them in?
My URL looks like this after the successfull facebook handshake
http://tmdb.app/auth/login/facebook?code=AQBTKNZIxbfdBruAJBqZ8xx9Qnz...
Code
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
return $authenticate->execute($request->has('code'), $this);
}
public function userHasLoggedIn($data)
{
$user = User::where('provider_id', $data->id)->first();
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
// NOT WORKING!
return redirect('test');
}
}
Your login function should be handling the redirect.
I'm guessing execute returns $data if the user is sucessfully logged in and false if not.
class SocialController extends Controller {
public function login(Authenticate $authenticate, Request $request)
{
if($data = $authenticate->execute($request->has('code'), $this))
{
$user = User::where('provider_id', $data->id)->first();
// maybe delegate the user creation to another class/service?
if( !$user )
{
$user = User::create([
'name' => $data->name,
'email' => $data->email,
'provider' => 'facebook',
'provider_id' => $data->id
]);
}
return redirect('test');
}
return redirect('fail_view');
}
}
You can do it using PHP header function in Laravel sub method. I try it and works properly. Hope it can help you.
// You can using the following code
$url= url("about-laravel");
header("Location:" . $url);
exit;
// Or using the following code to redirect and keep set flash message
$result= $this->yourMethod(); // return redirect($this->route)->with('flash_message', 'I\'m Flash Message'); for TRUE or NULL for false
if( $result ){
return $result;
}

Unique key validation showing error while updating data in laravel

Hi I am creating an application using laravel and i have a model where asset_number field is unique and the validation rules are as follows
MODEL
protected $rules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{id}',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
Here is my controller code for create and edit
CONTROLLER
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new Assetdetail instance
$assetdetail = new Assetdetail();
// attempt validation
if ($assetdetail->validate($new))
{
// Save the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function getEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
//$assetlife = DB::table('asset_details')->where('id', '=', $assetdetailId)->lists('asset_life');
$location_list = array('' => '') + Location::lists('name', 'id');
$assettype_list = array('' => '') + Assettype::lists('asset_type', 'id');
$assignTo_list = array('' => 'Select a User') + User::select(DB::raw('CONCAT(first_name, " ", last_name) AS full_name'), 'id') ->lists('full_name', 'id');
$assetdetail_options = array('' => 'Top Level') + DB::table('asset_details')->where('id', '!=', $assetdetailId)->lists('asset_number', 'id');
return View::make('backend/assetdetails/edit', compact('assetdetail'))->with('assetdetail_options',$assetdetail_options)->with('location_list',$location_list)->with('assettype_list',$assettype_list)->with('assignTo_list',$assignTo_list);
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
$new = Input::all();
/*if ($assetdetail ->asset_number == Input::old('asset_number') &&
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
}*/
if ($assetdetail->validate($new))
{
// Update the asset data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
My Route.php
Route::post('create', array('as' => 'savenew/assetdetail','uses' => 'Controllers\Admin\AssetdetailsController#postCreate'));
Route::get('{assetdetailId}/edit', array('as' => 'update/assetdetail', 'uses' => 'Controllers\Admin\AssetdetailsController#getEdit'));
Route::post('{assetdetailId}/edit', 'Controllers\Admin\AssetdetailsController#postEdit');
Now the problem is whenever i try to update my form my asset_number field throws an Error: The asset_number has already been taken.How do i pass the id in my controller while updating my form so that it throws error only if an already existing asset_number is used and not while editing the form with current asset_number.
I tried the following with no luck
Model
'asset_number' => 'mobileNumber' => 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Controller
Assetdetail::$rules['mobileNumber'] = 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Hi i finally found a working solution myself here is what i did please take a look
Controller
class AssetdetailsController extends AdminController
{
protected $validationRules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
public function postCreate()
{
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// attempt validation
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.assetdetail_not_exist'));
}
$this->validationRules['asset_number'] = "required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{$assetdetail->asset_number},asset_number";
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
}

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

Categories