Redirecting issues with CodeIgniter - php

I have a login script, and when the login is successful I want it to redirect them to the home page(welcome_message.php) for some reason it does not link me to this file, instead throws a 404 and says "The requested URL "http://localhost/musiclear/index.php/views/welcome_message" cannot be found or is not available. Please check the spelling or try again later."
I am using CodeIgniters redirect() function for the change.
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect('welcome_message'); //redirect to home page
} else { //incorrect username or password
$this->index();
}
}

Try passing the full URI to the redirect function like so:
redirect(base_url('views/welcome_message'));
Assuming of course that your controller is Views and page (function) is welcome_message

You can't redirect browser to view file directly, but You can redirect it to controller, which will show Your view. In Your example You're trying to access CodeIgniter's (which based in musiclear folder on Your localhost) Controller with name views and call welcome_message() method from it. But if Your really want to show it You must have next structure:
musiclear/
Application
Controllers
views.php
and views.php content:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Views extends CI_Controller {
function index() {
// default action, required method
}
function welcome_message(){
$this->load->view('welcome_message');
}
}
?>

actually when you make redirects in CodeIgniters it looks up for your controller and you should load view through the function of controller. e.g:
function validate_credentials() {
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if ($query) { // if users credentials validated
$data = array('usernames' => $this->input->post('username'),
'is_logged_in' => true);
$this->session->set_userdata($data); //set session data
redirect(base_url().'home/welcome'); //redirect to home function
} else { //incorrect username or password
$this->index();
}
}
function welcome(){
$this->load->view('welcome_mesage');
}

May be you forgot that redirect() function work only for controller class ie.
let you have welcomeclass so you can redirect it by using
redirect('wolcome');
you also redirect a function of controller class
if you want to redirect to page function of welcome controller class so you will writr
redirect('welcome/page');

Related

Not able to restrict user activities after successful login in codeigniter

i have a login process where the user can view his dashboard after login.
The code in controller:
$adminid = $this->am->login_admin($email, $password);
if ($adminid) {
$admin_data = array(
'adminid' => $adminid,
'email' => $email,
'logged_in' => true,
'loggedin_time' => time()
);
$this->session->set_userdata($admin_data);
$this->session->set_flashdata('login_success', 'You are logged in');
redirect('Admin_dashboard/dashboard/' . $adminid);
} else {
$this->session->set_flashdata('login_failed', 'Invalid login!!');
redirect('admin/index');
}
After successful login the user is getting redirected to the following url
localhost/project/Admin_dashboard/dashboard/1
The issue is that if the user manually changes the url to something like this-
localhost/project/Admin_dashboard/dashboard/2
he is able to access the data of user whose id is 2 without login
To solve the issue i tried using the following codition in the view
<?php if($this->session->userdata('logged_in')): ?>
<? endif; ?>
However the 2nd url is still accessible
After login the user gets redirected to dashboard that also contains few other pages such as profile page, payment page etc which contains data that is only related to him.
I want that after login he should be able to see all his pages but not anyone else data by changing the url
Simply do one thing, instead of passing $adminid with the url, get the adminid with session, because you also storing values in session.
Instead of
redirect('Admin_dashboard/dashboard/' . $adminid);
Use this
redirect('Admin_dashboard/dashboard');
and inside the dashboard function in Controller use this
public function dashboard (){
$admin_data = $this->session->userdata('admin_data');
if(!isset($admin_data['adminid']) || empty($admin_data['adminid'])){
//Error message Login First
redirect('admin/index');
}
$adminid = $admin_data['adminid'];
//Proceed with this $adminid
}
Simply add this code to all controllers for maintaining user restrictions throughout all URLs.
Class Controller_name extends CI_Controller{
function __construct(){
parent::__construct();
if(!isset($this->session->userdata['logged_in'])){
//redirect login page
}
}
/**
Your Other Functions
**/
}
Let me know If you have anymore doubts..
set user session is valid or not in dashboard controller before load dashboard view and also check user session adminid value with uri segment value
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
if (!$this->session->userdata('logged_in')) {
redirect('Login', 'refresh');
}else{
$uri_admin_val=$this->uri->segment(2);
$adminid=$this->session->userdata('adminid')
if($adminid!=$uri_admin_val){
redirect('Admin_dashboard/dashboard/' . $adminid);
}
}
}
}
And extend this my controller on dashboard and other controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dashboard extends MY_Controller {
public $data;
public function __construct() {
}
}

codeigniter: base_url part won't redirect to my controller

I am trying to make a log in work. I am all good with the verification but is stuck when it redirects to an another controller to show the view of the logged in page. I am still new to codeigniter and is still not sure about how controllers work.
This is my controller for verifying logged in users:
function index() {
$this->form_validation->set_rules('studentid', 'studentid', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE) {
$this->load->view('v_login');
} else {
//Go to private area
redirect(base_url('c_home'), 'refresh');
}
}
Its function is to validates the user if its in the database, however when the user is successfully logged in, it won't redirect to this redirect(base_url('c_home'), 'refresh'); It tells me that
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.
This is the c_home.php where it is supposed to be redirected:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('m_login','',TRUE);
$this->load->helper('url');
$this->load->library(array('form_validation','session'));
}
function index() {
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['studentid'] = $session_data['studentid'];
$this->load->view('v_home', $data);
} else {
//If no session, redirect to login page
redirect('c_login', 'refresh');
}
}
function logout() {
//remove all session data
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect(base_url('c_login'), 'refresh');
}
}
is it okay to redirect a controller from another controller?
after it redicts to c_home.php
it will show the v_home.php
<!DOCTYPE html>
<head>
<title>Simple Login with CodeIgniter - Private Area</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $studentid; ?>!</h2>
Logout
</body>
</html>
You don't need the base_url() in the redirect. just use
redirect('c_home',refresh);
Although there are 2 things i should make you aware of, you need ('controller/function') not just ('controller'). And also make sure you're loading $this->load->helper('url') in your __construct function on both controllers.
Although just for future reference, i think this is what you meant.
redirect(base_url().'c_home',refresh)
Codeigniter's redirect function already has the site_url() embedded.
So, instead of this;
redirect(base_url('c_login'), 'refresh');
Use this, as you have earlier in your code
redirect('c_login', 'refresh');
Hope this helps

CI routing issue

i am currently learning CI and i have come to an issue that i cant seem to solve.
i set up my wamp server in a drive and inside the www(root) folder i have extracted the codeigniter files.
![example][1][1]: http://i.stack.imgur.com/7RKqG.png
then I created my php files for view/model and controller and set the default route in the config/routes.php
so now when I go to my browser and type localhost I get the post.php displayed without anyissue.
but I am unable to access any of the views from here. for example i have a new_post.php view and when i type in the address bar localhost/new_post.php i get a "Not Found
The requested URL /new_post.php was not found on this server." error.
what am i doing wrong? below i have posted the code which i have written in the post.php controller along with a image of the file structure/names i have.
posts.php - controller
<?php
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('post'); //loads the post model u created in the models folder
}
function index() //goes to this function 1st when u access the controller
{
$data['posts']=$this->post->get_posts(); // load all the data from the get_posts function in post model to the data array posts
$this->load->view('post_index', $data); //loads the view
}
function post($postID)
{
$data['post']=$this->post->get_post($postID);
$this->load->view('post', $data);
}
function new_post()
{
if($_POST)
{
$data=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' =>1
);
$this->post->insert_post($data);
redirect(base_url(). 'posts/');
}
else
{
$this->load->view('new_post');
}
}
function editpost($postID)
{
$data['success']=0;
if($_POST)
{
$data_post=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' => 1
);
$this->post->update_post($postID,$data);
$data['success'] =1;
}
$data['post']=$this->post->get_post($postID);
$this->load->view('edit_post',$data);
}
function deletepost($postID)
{
$this->post->delete_post($postID);
redirect(base_url(). 'posts/');
}
}
![structure][1] [1]: http://i.stack.imgur.com/SnsbW.png
In CodeIgniter you have to use controller to get access to his function
you are saying "when i type in the address bar localhost/new_post.php i get a Not Found" because you try to direct access its function name you have to use example.com/controllername/functionname like this
http://localhost/posts/new_post
for more information check codeignier url
https://ellislab.com/codeigniter/user-guide/general/urls.html
if you not removed index.php using .htaccess then you have to use your url like this
http://localhost/index.php/posts/new_post
In CodeIgniter, everything runs through the main "index.php" file, in your root directory.
So, you would access your new post page, like this;
http://localhost/index.php/posts/new_post
Have a read through the CodeIgniter user guide, it will answer any problem you have.
https://ellislab.com/codeigniter/user-guide/

How to redirect user to a different controller on refreshing the page

I am working on codeigniter. I am implementing signin functionality and when user signs in i call this controller
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query==1)
{
$data = array
(
'username'=>$this->input->post('username'),
'is_logged_in' => true
);
$email=$data['username'];
$this->session->set_userdata('email_of_user',$email);
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$data['result']=$this->membership_model->friend_notify($one);
$data['count']=$this->search_peoplee->get_friends_count($one);
$this->load->model('search_peoplee');
$data['values']= $this->search_peoplee->get_notifications($one);
$data['count_notify']=$this->search_peoplee->get_notifications_count($one);
$this->session->set_userdata('lookatit','no');
$this->load->view('home_screen',$data);
}
elseif($query==2)
{
$data['main_content']='email_not_found';
$this->load->view('includes/template',$data);
}
else
{
$this->error_index();
}
}
this validates the credentials and stores a session, this controller calls a model "$this->membership_model->validate();" which picks the value form view and check that if user exists, the problem is when i retype the address it takes me to the login page and says sign in again as the model reads empty values. How to avoid this. help!!!
after you have authenticated, how about setting a session variable.
so,
$this->session->set_userdata('authenticated',TRUE);
then in the controller, first check if the user is authenticated and do a redirect, otherwise go to the validate_credentials method ??

Changing content when user has logged in i.e. when session starts

How do I change the content for a user when he logs in? I mean like enabling voting, changing "login" to "logout" etc.
What I think to do is to start the session when user logs in (I am preferring to start session only when user logs in, not all the time). Then add data to the session's cookie like-
//controller
$moredata = array(
'username' => $this->username,
'login' => TRUE
);
$this->session->set_userdata($modedata);
//redirect
Then in the other controller, where he has been redirected I check the following-
$login = $this->session->userdata('login');
if ($login==TRUE)
Depending on the 'if' condition I will pass a variable to the view, with the help of that variable I will forward only the div/sections which should be shown to a logged-in user.
The problem is, while performing the above comparison Codeigniter shows following error (remember I haven't added 'session' in autoload array yet)
Message: Undefined property: NameOfController::$session
And If I set following in the autoload file
$autoload['libraries'] = array('session');
then the "if ($login==TRUE)" comparison always shows FALSE.
What should I do?
If I were you, I'd place all your session checks in a base controller which all your other main controllers extend. This allows you to keep things DRY:
class BaseController extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
// Will return true or false
return $this->session->userdata('login');
}
}
And in one of your functional controllers (the example below handles users):
class UserController extends BaseController {
public function __construct()
{
parent::__construct();
}
public function profile()
{
// Redirect if not logged in
if (!$this->isLoggedIn()) {
$this->redirect('some/other/page')
}
}
public function register()
{
// Show different HTML if not logged in
$data = array(
'isLoggedIn' => $this->isLoggedIn()
);
$this->load->view('register', $data);
}
}
The second method in UserController allows you to render different content in your view:
<? if ($isLoggedIn): ?>
<p>You're logged in!</p>
<? else: ?>
<p>Not logged in</p>
<? endif; ?>
On my last project we created a simple permissions helper that had functions to check for logged-in status and for privilege levels. Then we'd just call the helper's functions as needed from anywhere in the system. If the user is logged in and has privs for that content then they get the content - otherwise we'd redirect them to a registration or other error page. Since all of that logic is in the helper functions, we could wrap any permission-requiring code in a quick permissions call like if(is_logged_in()){code requiring login to access}.

Categories