Laravel session won't change - session

I'm trying to change website language using the "site_lang" session key. Here's the Controller
public function __construct()
{
if( !session()->has( 'site_lang' ) ) { session(['site_lang' => 'en']); }
$this->lang = session()->get('site_lang');
app()->setLocale($this->lang);
User clicks another language link to change website lang so he gets redirected to this function in the HomeController which extends Controller
session()->forget('site_lang');
session(['site_lang' => $lang]);
//echo session()->get('site_lang').'<br>'; //prints fr
$this->lang = $lang;
//echo $this->lang; //prints fr
app()->setLocale($lang);
//echo app()->getLocale(); //prints fr
return redirect("/");
Removed some validations to make it brief
So the user clicks "French" and gets redirected to "HomeController#change_lang" which is the previous function and all echo statements prints fr but when the user gets redirected to the home page the value gets assigned again to en by this line
if( !session()->has( 'site_lang' ) ) { session(['site_lang' => 'en']); }
Why does this happen and how to solve it?

SESSION can't be accessed from the constructor unless following a work around like laravel - Can't get session in controller constructor

Related

Codeigniter 3 login check function not showing correct flashdata messages

I am creating a login check function. But my two flash data messages are not setting correct.
If user has logged on and then if the session expires it should set this
flash data message Your session token has expired!
And if the user has not logged on and tries to access a controller with out logging on
then it should set this flashdata message You need to login to
access this site!
For some reason it is always showing the second flashdata message.
Question: How am I able to use the two flashdata messages properly.
Controller: Login.php
Function: check
public function check() {
$uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class();
$route = isset($uri_route) ? $uri_route : '';
$ignore = array(
'common/login',
'common/forgotten',
'common/reset'
);
if (!in_array($route, $ignore)) {
// $this->user->is_logged() returns the user id
if ($this->user->is_logged()) {
// $this->session->userdata('is_logged') returns true or false
if (!$this->session->userdata('is_logged')) {
// Redirects if the user is logged on and session has expired!
$this->session->set_flashdata('warning', 'Your session token has expired!');
redirect('admin/common/login');
}
} else {
$this->session->set_flashdata('warning', 'You need to login to access this site!');
redirect('admin/common/login');
}
}
I run function via codeigniter hook that way I do not have to add it on every controller.
$hook['pre_controller'] = array(
'class' => 'Login',
'function' => 'check',
'filename' => 'Login.php',
'filepath' => 'modules/admin/controllers/common'
);
What are you trying to check via the uri() is actually a very bad way of checking, also you should include login checks as a construct function not single.. here is what your function should look like:
function __construct()
{
parent::__construct();
if (!$this->session->userdata('logged_in')) {
// Allow some methods?
$allowed = array(
'some_method_in_this_controller',
'other_method_in_this_controller',
);
if (!in_array($this->router->fetch_method(), $allowed)
{
redirect('login');
}
}
}

CodeIgniter - Load View after Update

After I have updated a customer (which works fine)
public function update($customer_acc) {
if($this->session->userdata('logged_in'))
{
$id= $this->input->post('did');
$data = array(
'customer_name' => $this->input->post('dname')
);
$this->load->model('update_model');
$this->update_model->update_customer($id,$data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
How can i then load back the view customer function. What i need is after the update has been completed so then go back to viewing the customer.
public function view($customer_acc) {
if($this->session->userdata('logged_in'))
{
$this->load->model('display_single_customer');
$customers = $this->display_single_customer->view_single_customer($customer_acc);
$data['customer_acc'] = $customers['customer_acc'];
$data['customer_name'] = $customers['customer_name'];
$this->load->view('customers_single_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
you just exit to another method in your controller to show the new page. for passing the id you can either pass it directly
if ( some condition ) {
$id = $this->input->post('did', TRUE);
// blah blah blah
// success -- now go to show customer method
$this->showCustomer($id) ; }
function showCustomer($id){
// get the customer to display using the $id that was passed
$customers = $this->display_single_customer->view_single_customer($id);
OR you can declare the id with $this-> and then it is available to any method in the controller
$this->id = $this->input->post('did', TRUE);
// blah blah
$this->showCustomer() ; }
function showCustomer(){
// get the customer to display using $this->id
$customers = $this->display_single_customer->view_single_customer($this->id);
// etc etc
I think i may have sussed it I can use a redirect using the $id which is the customer account number
redirect("/customers/view/$id");
Is this the correct way, It works but is it best practice ?

Codeigniter: Controller function name shows in url, how change to view file name?

wondering if anyone can guide me to what ive done wrong (or need to do) and think the problem is in my routes file. When the user is displayed the login form and for example they get their username wrong after submit the url displays as this: http://localhost:8888/codeigniter/login/login_validation. When the are successful and log into the admin area (which pulls news articles from the db) this url is still shown. I am wondering if there is a way to make it to http://localhost:8888/codeigniter/news. I have looked in my routes folder and i tried to use 'wildcards' and was unsuccessful. Here is my code for reference, any other info or files needed let me know! Thanks.
CONTROLLER:
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('login');
}
//Validate login area
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required|xss_clean|callback_password_check');
if($this->form_validation->run() == FALSE) {
//Field validation failed. User redirected to login page
$this->index();
}else{
$this->load->model('user_model');
$query = $this->user_model->login_details();
// if the user's credentials validated...
if($query) {
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('news');
}else{
$data['error'] ="Invalid Username or Password";
$this->load->view('login',$data);
}
}
}
function logout() {
$this->session->sess_destroy();
$this->index();
}
}
login_details function from user_model.php
function login_details() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('login');
if($query->num_rows == 1){
return true;
}
}
If you're logging into any kind of system, you're going to need to store a session using CodeIgniter's Session class. Provided controllers/news.php exists, you can set the session and immediately just perform a redirect with redirect('news');. No need to $this->load->view() because this logic will be in news.php's index anyway and you'd be duplicating code.
I'm not sure what $this->user_model->login_details() is returning, but I'm assuming false or null because you say CodeIgniter is sending you back to the login view. Head into the login_details() function and make sure things are working properly (you might want to post it too). Also, post your routes.php file for us if you made changes just in case.
On a side note: Space is a valid password character, don't trim it or folks with leading or trailing space's in their passwords won't be able to get in ;)

Redirection In index.php page in Codeigniter

Iam developing a site in codeigniter.This is my url http://myserver.net/visio/UBwXo.
Here http://myserver.net/visio/ is my base_url.
After /visio/ here have a variable.When there have any value after /visio/ then i wantto take the corresponding url from database to this value.
That means in my database,
UBwXo => "*any url***"
jshom => "*any url***"
So when getting value after /visio/ i want to take the corresponding url from databse and redirect it in to that url without using htaccess.
I want to done this redirection process in index.php page of root folder.
Is this possible?
The orginal url for http://myserver.net/visio/UBwXo like myserver.net/visio/index.php/admin/index/UBwXo
the default controller is admin
First, create redirect.php file in the controllers folder (application/controllers) and add this code to this file:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Redirect extends CI_Controller
{
/**
* Method to redirect from an alias to a full URL
*/
public function index()
{
$alias = $this->uri->segment(1);
$this->db->select('url');
$query = $this->db->get_where('links', array('alias' => $alias), 1, 0);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$this->load->helper('url');
redirect($row->url, 'refresh', 301);
}
}
else
{
echo "Sorry, alias '$alias' not found";
}
}
}
Then create table in your database. Your table must be like this:
CREATE TABLE IF NOT EXISTS `links` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`alias` varchar(6) CHARACTER SET utf8 DEFAULT NULL,
`url` text CHARACTER SET utf8,
PRIMARY KEY (`id`),
UNIQUE KEY `alias` (`alias`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
After that, set default controller value to the redirect class.
Open application/config/routes.php. Find $route['default_controller'] , then set redirect as a value to this variable, like this:
$route['default_controller'] = "redirect";
Then enjoy life ;)
EDIT:
I had forgotten to mention URI routing in config/routes.php for redirecting:
$route[':any'] = "redirect/index/$1";
Your best resource here will be the CodeIgniter guides, specifically the page on Controllers. The section on Remapping Function calls should be exactly what you need in this case.
Since the default behavior is to look for a controller method with the name of the first segment after the base url, we need to change this to pass it as an argument to some function. Your controller might look something like this:
class Shortener extends CI_Controller {
private function shorten( $token ){
// Find the URL that belongs to the token and redirect
}
public function _remap( $method, $params = array() ) {
// Catch other controller methods, pulled from the CodeIgniter docs
if ( method_exists( $this, $method ) ) {
return call_user_func_array( array( $this, $method ), $params );
}
$this->shorten( $method );
}
}

KO3 - Kohana 3 - How can I pass $_POST data from a controller/action back to the view/form that called it?

I am trying to validate a form submission in Kohana 3. I have the form::open point to my action_create in my controller which successfully validates the data posted to it from the form in my view. If the data passes validation, a new item is created as intended, and the user is redirected to the item that was just created. This works correctly. If the data fails validation, however, I would like the user to be directed back to the originating view/page while retaining a variable containing the data that was posted so that I can repopulate the form and display errors.
In short, how can I pass data from a view -> controller -> original view?
Thank you, everyone!
The user also posed this question on the Kohana forums.
Those seeking an answer to this should have look over there.
I assume you're using Controller_Template.
File views/form.php:
// Set default variables if variables not passed to this view
$username = isset($username) ? $username : '';
echo Form::open('login');
// Input: username
echo Form::label('username', 'Username');
echo Form::input('username', $username);
echo isset($errors['username']) ? $errors['username'] : '';
// Input: username
echo Form::label('password', 'Password');
echo Form::input('password', $password);
echo isset($errors['password']) ? $errors['password'] : '';
echo Form::close();
File views/template.php
<html>
<head><title>My Website</title></head>
<body>
<?php echo isset($content) ? $content : ''; ?>
</body>
</html>
File classes/controller/user.php
Class Controller_User extends Controller_Template {
public $template = 'template';
public function index()
{
$this->template->content = $this->display_form('form');
}
public function login()
{
// Setup validation & rules here
// Check validation, assume $validation is Validation object
if ($validation->check()
{
// Validation succeeded. Do anything you want here
}
else
{
// Validation failed. Display form with entered values
$form_vars = $_POST;
$form_vars['errors'] = $validation->errors();
// Display form
$this->template->content = $this->display_form('form', $form_vars);
}
}
// Displaying form
private function display_form($form_file, $form_vars=NULL)
{
$form = View::factory($form_file);
if ($form_vars != NULL)
{
foreach($form_vars as $key => $value)
{
$form->$key = $value;
}
}
return $form;
}
}
Hope that helps!

Resources