unset session on direct access to a function in codeigniter - codeigniter

I have 2 functions in my controller that I'm sending a session using the first one to the second function. What I am talking about is:
public function search()
{
$search_term = $this->input->post('search_term');
$this->session->set_userdata('search_term', $search_term);
redirect('search_result/');
}
and the second function:
function search_result()
{
$search_term = $this->session->userdata('search_term');
$data['search_term'] = $search_term;
$this->load->view('includes/template', $data);
}
Everything is fine but, the problem is that, I want to prevent direct access to search_result() function. I mean, I want to unset search_term session when the user calls search_result() directly. What should I do?!

You can use flashdata: http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages
And this is the code that do what are you looking for:
public function search()
{
$search_term = $this->input->post('search_term');
$this->session->set_flashdata('search_term', $search_term);
redirect('search_result/');
}
function search_result()
{
$search_term = $this->session->flashdata('search_term') ? $this->session->flashdata('search_term') : '';
$data['search_term'] = $search_term;
$this->load->view('includes/template', $data);
}

There are many ways you can do it. Here are some
append a get parameter if it exists then search else redirect back
public function search()
{
$search_term = $this->input->post('search_term');
$this->session->set_userdata('search_term', $search_term);
redirect('search_result?status=1');
}
public function search_result()
{
$status = $this->input->get('status');
if(status == 1){
$search_term = $this->session->userdata('search_term');
$data['search_term'] = $search_term;
$this->load->view('includes/template', $data);
}else{
$this->session->unset_userdata('search_term');
redirect('search');
}
}
Protect you seach_result function and dont let user direct call it.
Using _ will do it for you.
Here is the link you can read.
public function search()
{
$search_term = $this->input->post('search_term');
$this->session->set_userdata('search_term', $search_term);
$this->_search_result($search_term);
}
function _search_result($keyword)
{
if(strlen($keyword)>0){
$data['search_term'] = $keyword;
$this->load->view('includes/template', $data);
}else{
redirect('search');
}
}

in the search function
redirect('search_result/'.$this->session->userdata('search_term'));
in the search_result function
function search_result()
{
if($this->uri->segment(3))
{
$search_term = $this->session->userdata('search_term');
$data['search_term'] = $search_term;
$this->load->view('includes/template', $data);
}
else
{
redirect('search_result/','refresh');
}
}
hope it will help you.please let me know if you face any problem.

Related

Filtering and searching in codeigniter

I am doing a filtering and searching in codeigniter but no idea! how to do that?
but i try my best but fail!!!
here i show the list which is shown by ajax that sucess
MY DATA BASE ARE
MY CONTROLLER IS
public function get_quick_search()
{
$sepcli= $this->input->post('spec');
$distct= $this->input->post('dist');
$locat= $this->input->post('locat');
$data['list'] = $this->Doctor_model->search_listing();
$data['quck_search'] = $this->search_model->get_quick_list($sepcli,$distct,$locat);
$data['get_specs'] = $this->specialisation_model->get_specialisation();
$this->load->helper(array('form', 'url'));
$this->load->view('customer/header');
$this->load->view('customer/side_view',$data);
$this->load->view('customer/quick_search',$data);
$this->load->view('customer/footer');
}
MY MODEL LIKE
public function get_quick_list($locat,$distct,$sepcli)
{
$this->db->select('*');
$this->db->from('tbl_doctor');
$this->db->join("tbl_specialisation", "tbl_specialisation.spec_id = tbl_doctor.spec_id",'left');
$this->db->where("(district LIKE '$distct' AND place LIKE '$locat' AND spec_specialise LIKE '$sepcli')");
$query=$this->db->get()->result_array();
return $query;
}
HERE NO ERROR SHOW BUT THE RETURN QUERY IS NULL SHOW LIKE THIS (array(0) { })
you might try like this ,Your Controller function code
public function get_quick_search()
{
$s_data['sepcli'] = $this->input->post('spec');
$s_data['distct'] = $this->input->post('dist');
$s_data['locat'] = $this->input->post('locat');
$data['quck_search'] = $this->search_model->get_quick_list($s_data);
$data['get_specs'] = $this->specialisation_model->get_specialisation();
$this->load->helper(array('form', 'url'));
$this->load->view('customer/header');
$this->load->view('customer/side_view',$data);
$this->load->view('customer/quick_search',$data);
$this->load->view('customer/footer');
}
your model function code
public function get_quick_list($s_data)
{
$this->db->select('td.*, ts.*')
$this->db->from('tbl_doctor as td');
$this->db->join('tbl_specialisation as ts', 'ts.spec_id = td.spec_id','left');
if($s_data['sepcli'] !="")
$this->db->like('ts.spec_specialise',$s_data['sepcli'],'both');
if($s_data['distct'] !="")
$this->db->like('td.district',$s_data['distct'],'both');
if($s_data['locat'] !="")
$this->db->like('td.place', $s_data['locat'], 'both');
$query=$this->db->get()->result_array();
return $query;
}
sure it will helps , you should try it !!!

API REST don't work routes

I'm using codeigniter, for make an api rest, with the library that provide the oficial web site.
The problem is: the file routes.php doesn't redirect well. When i put localhost/API/1 into my browser apear the 404 error.
Here my controller "Apicontroller":
public function __construct() { //constructor //no tocar
parent::__construct();
$this -> load -> model("Modelocontrolador");
}
public function index_get() { //get all the info
$datos_devueltos = $this->Modelocontrolador->getPrueba(NULL, "Usuarios");
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}
public function find_get($id){ //select where
$datos_devueltos = $this->Modelocontrolador->getPrueba($id, "Usuarios");
if($id != NULL){
if(!is_null($datos_devueltos)){
$this->response(array("response" => $datos_devueltos), 200);
}else{
$this->response(array("response" => "No date"), 200);
}
}else{
$this->response(array("response" => "No dates for search"), 200);
}
}
public function index_post() { //insert in la table
if(! $this -> post("dato")){
$this->response(array("response" => "No enought info"), 200);
}else{
$datoID = $this -> Modelocontrolador -> save($this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => $datoID), 200);
}else{
$this->response(array("response" => "No found it"), 200);
}
}
}
public function index_put($id) { //"update"
if(! $this -> post("dato") || ! $id){
$this->response(array("response" => "No ha mandado informacion correcta para el update"), 200);
}else{
$datoID = $this -> Modelocontrolador -> update("Uid",$id,$this -> post("dato"),"UsuariosJJ");
if(!is_null($datoID)){
$this->response(array("response" => "Dato actualizado"), 200);
}else{
$this->response(array("response" => "Error modify"), 200);
}
}
}
public function index_delete($id) {
if(! $id){
$this->response(array("response" => "Not enought info"), 200);
}else{
$delete = $this-> Modelocontrolador -> delete("Uid",$id,"UsuariosJJ");
}
if(!is_null($delete)){
$this->response(array("response" => "Date delete"), 200);
}else{
$this->response(array("response" => "Error delete"), 200);
}
}}
And my routes file:
$route['default_controller'] = 'Apicontroller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
/*sub-rutas*/
/*---------*/
$route["Apicontroller"]["get"] = "Apicontroller/index"; //basico
$route["Apicontroller/(:num)"]["get"] = "Apicontroller/find"; //select
$route["Apicontroller"]["post"] = "Apicontroller/index"; //insert
$route["Apicontroller/(:num)"]["put"] = "Apicontroller/index/$1"; //update
$route["Apicontroller/(:num)"]["delete"] = "Apicontroller/index/$1"; //delete
If the browser request literally uses /API then routing needs to 'see' exactly that. Also, the route rules must be explicit with the method to be called. (Hopefully the code shown reflects the mapping you had in mind.)
/*sub-rutas*/
/*---------*/
$route["API"]["get"] = "Apicontroller/index_get"; //basico
$route["API/(:num)"]["get"] = "Apicontroller/find_get/$1"; //select
$route["API"]["post"] = "Apicontroller/index_post"; //insert
$route["API/(:num)"]["put"] = "Apicontroller/index_put/$1"; //update
$route["API/(:num)"]["delete"] = "Apicontroller/index_delete/$1"; //delete
Using the above routes I created some test code. Here are those files.
The much simplified Apicontroller.
class Apicontroller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index_get()
{
echo "API index";
}
public function find_get($id)
{ //select where
echo "API find_get $id";
}
public function index_post()
{
echo 'API index_post';
}
public function index_put($id)
{ //"update"
echo "API put $id";
}
}
I don't believe that because your Apicontroller is extending a different Class the results would change. That may be a drastic assumption.
In order to test POST calls I used these two files.
First a Testpost.php controller
class Testpost extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
}
public function index()
{
$this->load->view("test");
}
}
The very simple view (test.php) loaded by the above.
<?php
echo form_open("API");
echo form_submit('mysubmit', 'Submit Post!');
echo form_close();
Directing the browser to localhost/testpost shows a page with a single submit button. Pressing the button results in a screen with the text "API index_post".
Sending the browser to localhost/API/3 produces a screen with the text "API find_get 3".
localhost/API produces "API index".
Now the interesting thing (not related to your problem, but interesting).
Given the default
$route['default_controller'] = 'Apicontroller';
and the route
$route["API"]["get"] = "Apicontroller/index_get";
I expected that directing the browser to the home page localhost would produce "API index". But it doesn't. It results in a 404. Due to that behavior it might be wise to be more explicit with default_controller
$route['default_controller'] = 'Apicontroller/index_get';
Or add an index() function to Apicontroller that calls $this->index_get().
I did not test PUT or DELETE as my server isn't setup to handle them. But as GET and POST seem to function, in a righteous world, they will work.
seems like you are using PHil's REST_Controller library with CI 2.x, correct ?
If so, I would recommend you to use what I like to call an "index gateway" because you can't do per-Method routing with CI2:
class Apicontroller extends REST_Controller
{
function index_gateway_get($id){
$this->get_get($id);
}
function index_gateway_put($id){
$this->put_put($id);
}
// This is not a "gateway" method because POST doesn't require an ID
function index_post(){
$this->post_post();
}
function get_get($id = null){
if(!isset($id)){
// Get all rows
}else{
// Get specific row
}
}
function put_put($id = null){
if(!isset($id)){
// a PUT withtout an ID is a POST
$this->post_post();
}else{
// PUT method
}
}
function post_post(){
// POST method
}
}
The routing to make this work is really easy:
$route["API/(:num)"] = "Apicontroller/index_gateway/$1";
That's all you need. Phil's REST Library will redirect to the correct index_gateway_HTTPMETHOD depending on which method is used.
Each index_gateway_HTTPMETHOD will then redirect to the correct method.
As far as I know, this trick is the only way to have CI2 use a single /API/ entry point that works for all HTTP Methods.

Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path#index'
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path#index' with $id, $start, and $end?
});
There is no way to call a controller from a Route:::get closure.
Use:
Route::get('/path/{id}/{start?}/{end?}', 'Controller#index');
and handle the parameters in the controller function:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
This helped me simplify the optional routes parameters (From Laravel Docs):
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Or if you have a controller call action in your routes then you could do this:
web.php
Route::get('user/{name?}', 'UsersController#index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
I hope this helps someone simplify the optional parameters as it did me!
Laravel 5.6 Routing Parameters - Optional parameters
I would handle it with three paths:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Note the order - you want the full path checked first.
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Find more details here (Laravel 7) : https://laravel.com/docs/7.x/routing#parameters-optional-parameters
You can call a controller action from a route closure like this:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
What I did was set the optional parameters as query parameters like so:
Example URL:
/getStuff/2019-08-27?type=0&color=red
Route:
Route::get('/getStuff/{date}','Stuff\StuffController#getStuff');
Controller:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
Solution to your problem without much changes
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
return App\Http\Controllers\HomeController::Path($id,$start,$end);
});
and then
class HomeController extends Controller
{
public static function Path($id, $start, $end)
{
return view('view');
}
}
now the optimal approach is
use App\Http\Controllers\HomeController;
Route::get('/path/{id}/{start?}/{end?}', [HomeController::class, 'Path']);
then
class HomeController extends Controller
{
public function Path(Request $request)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
//your code
return view('view');
}
}

CodeIgniter: My upsert function not working with my_model / my_controller

Working with the my_model & my_controller for the first time this month within CodeIgniter, I think I almost have this working.
I got an insert function working properly, now I'm trying to add an update to it if there is an ID.
Here's my code:
function upsert_client($client_id = 0)
{
load_model('client_model');
$this->insertMethodJS();
$this->fields['client'] = $this->_prototype_client();
$user_id = get_user_id();
$company_id = get_company_id();
if ($client_id)
{
$this->data['client'] = $this->client_model->get_record($client_id);
}
if (!$this->ion_auth->in_group(GROUP_NAME_MANAGER, $user_id))
{
redirect('members/dashboard');
}
if ($_POST)
{
$this->load->helper('string');
if ($this->_validate_client())
{
$fields = $this->input->post(null , TRUE);
$fields['user_id'] = $user_id;
$fields['company_id'] = $company_id;
$fields['active'] = 1;
if ($client_id)
{
$fields['id'] = $this->client_model->get_record($client_id);
unset($fields['billing']);
$this->client_model->update($client_id, $fields);
}
else
{
unset($fields['billing']);
$this->client_model->insert($fields);
redirect('members/clients/manage_clients');
}
}
}
$this->template->write_view('content',$this->base_path.'/'.build_view_path(__METHOD__), $this->data);
$this->template->render();
}
function _prototype_client()
{
$fields = array();
$fields['id'] = 0;
$fields['name'] = '';
return $fields;
}
And from my client_model:
class Client_model extends MY_Model {
function get_record($client_id)
{
$query = $this->db->select('id')
->where(array('id'=>$client_id))
->get('clients');
return $query->row_array();
}
}
Everytime I try to edit a "client", it just inserts a new one... All I'm currently trying to edit is the "name" field.
My edit button:
<td><button class="btn btn-inverse" style="float: right;" type="button">Edit</button></td>
Any help is appreciated, thanks! And let me know if you need any additional details...
I never worked with ion auth in particular but from what I see you have a couple of functions that are not referenced correctly.
load_model('client_model');
//Should be
$this->load->model('client_model');
also a few other functions should be referenced as
$this->function_name();
//Instead of just
function_name();
//Unless they are in another library
$this->lib_name->function_name();
I'm not sure if this well solve your problems but just a few things I noticed.
Your hyperlink points to 'add_client' whereas the function you are showing is called 'upsert' Are you calling the correct URL?

Form validation with custom callback function

I created a "callback" function to check if the username exists in the DB.
I have multiple rules for the "username" field, but the only thing that work is my callback function. It refuses to check against the other rules. I tried leaving the field empty, and the "required" rule never kicked in.
Controller:
account.php
function register() {
$this->load->library('validation');
$fields['username'] = "trim|required|callback_username_check";
etc ...
etc ...
$this->validation->set_rules($fields);
if ($this->validation->run()) {
$records = array();
$records['username'] = $this->validation->username;
etc ...
etc ...
$data = $this->account_model->registerNewAccount($records);
}
$this->load->view('register_view');
}
function username_check($username) {
$m = new Mongo();
$collection = $m->selectDB( DBNAME )->selectCollection( TABLE );
$data = $collection->count(array("username" => $username) );
if($data == 1) {
$this->validation->set_message('username_check', '%s is already taken!');
return false;
} else {
return true;
}
}
Try using the new form_validation class here:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html
I believe there was a bug about it.

Resources