I'm trying to create a login system but it doesn't seem to set "Session=true". Please help I'm stuck with this for too long now.
Session starts
Checked all my code
No PHP errors
and No database Errors
Login Page:
if($session->is_logged_in()) {
redirect_to("index.php");
}
if (isset($_POST['submit'])) { // Form has been submitted.
$user_name = trim($_POST['user_name']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($user_name, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
} else {
// username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else { // Form has not been submitted.
$user_name = "";
$password = "";
}
Session Class:
class Session {
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
// database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
index page:
if (!$session->is_logged_in()) { redirect_to("login.php");
Authorize Method:
public static function authenticate($user_name="", $password="") {
global $database;
$user_name = $database->escape_value($user_name);
$password = $database->escape_value($password);
$sql="SELECT * FROM users WHERE user_name='{$user_name}' AND password ='{$password}' LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
Change your is_logged_in() function to:
public function is_logged_in() {
$this->check_login();
return $this->logged_in;
}
Otherwise is_logged_in() will always return false on each new request (such as redirecting between pages). By calling check_login() first, it will set the logged_in variable with the value (true or false, dependent on if $_SESSION['user_id'] is set.
EDIT:
I'm sorry, I've overlooked the line in the constructor where you already call $this->check_login();
Another thing is that the authenticate function returns an Array instead of an object. So, change the following:
$this->user_id = $_SESSION['user_id'] = $user->id;
To
$this->user_id = $_SESSION['user_id'] = $user['id'];
Finally I have found the solution to this.
Guess what? It wasn't my codes fault but it was my servers(WAMP 2) fault. So, I uninstalled WAMP 2 and updated to the newer version WAMP 2.5. Solved my problem and no more getting redirect to login page!
Related
I have this session class
class Session
{
public function __construct()
{
if (!isset($_SESSION)) {
$this->initSession();
}
}
public function setSessionId()
{
$_SESSION['Id'] = session_id();
}
public function getSessionId()
{
return $_SESSION['Id'];
}
public function initSession()
{
session_start();
error_reporting(E_ALL);
$this->setSessionId();
}
public function isLogged(){
if(isset($_SESSION['Id'])){
return true;
}else{
$this->deleteSession();
return false;
}
}
In my login.php I pass the id to my session but
$results['Id'] = session_id();
when I got to index.php and echo the Id it echos a long string not the current user Id
$session = new Session();
$id = $session->getSessionId();
echo $id;
Please help me how do I pass the variable!I have tried a lot but I seem to be stuck here!Would really appreciate some help
Add additional methods to your class:
public function setUserId($userid) {
$_SESSION['user_id'] = $userid;
}
public function getUserId() {
return isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
}
Then your login page should call $session->setUserId() after the user logs in, passing the ID from the database.
could use help with a simple code with both PHP and SQL (PDO) :)
Trying to access a table, withdraw 1 row from 1 column with specific details using MVC and then verifying said info, building it and then entering that info into Session storage so that I can validate what "role" and "user" is present at a certain time.
That's my controller
<?php
class PagesController {
public function home() {
$first_name = 'Qwerty';
$last_name = 'Qwerty';
require_once('views/pages/home.php');
}
public $admin_model;
public function __construct() {
$this->admin_model = new Admin();
}
public function login() {
session_start();
$log = $this->admin_model->LoginModel();
if($log == true){
$admin= $this->admin_model->findAdmin($_POST['user'],$_POST['pass']);
if($admin == true){
$_SESSION['user'] = $admin['user'];
print_r($_SESSION);
}
require_once('views/pages/login.php');
}else if($log == false){
echo "There is no existing account with that information. Please try a different account.";
require_once('views/pages/home.php');
}
}
?>
And this is my Admin Model.
<?php
require_once 'connection.php';
class Admin{
public $name;
public $role;
public $phone;
public $email;
public $password;
public $img;
public $id;
public function __construct() {
}
public function LoginModel(){
if(isset($_POST['user'])&&($_POST['pass'])){
$name= $_POST['user'];
$password=$_POST['pass'];
}
else{
$name='NULL#NULL';
$password='NULL';
}
$db = Db::getInstance();
$sql = $db->prepare('SELECT * FROM `admin` WHERE "Name" = "'.$name.'" AND Password = ' . $password .' ');
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
if($result >= 1){
return true;
}else{
return false;
}
}
public function findAdmin($name, $password){
$db = Db::getInstance();
$sql = $db->prepare('SELECT * FROM `admin` WHERE "Name" = "'.$name.'" AND Password = ' . $password .' ');
$sql->execute();
$result = $sql->setFetchMode(PDO::FETCH_ASSOC);
if($result > 0){
return $result;
}
}
}
Now, the first one, the Login() model works, BUT it doesn't matter what $_POST['user'] or $_POST['pass'] I input it always works :/... so it seems my SQL query always returns a true (i'm inputting the same into as found in the table, username "admin" and password "12345" but no matter what information I put in? it works. which is odd..
Second of all I want to "Find" the admin after login in and putting that info into a session that I can verify on every view... any help?...
I think your specific problem is that you're using the return of setFetchMode() as an indicator of whether or not rows were found by the execution. Since its return value is TRUE simply by virtue of it succeeding in setting the fetch mode, you're probably always going to see TRUE returned.
You probably need to do fetchAll() and count the records in the array, if all you want to do as verify that at least one row was returned.
Hi am getting this error when I am trying to send a redirect to the login page.
here is my code...
The localhost page isn’t working
localhost redirected you too many times. Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
anything I am trying it's giving me this error.
any suggestions would be much appreciated, thank you!
<?php
if(!$session->is_signed_in()){
header("Location:login.php");
} else{
header("Location:logout.php");
} ?>
and this
class Session{
private $signed_in = false;
public $user_id;
public function __construct(){
session_start();
$this->check_the_login();
}
// check the value of signed in property - getter method
public function is_signed_in(){
return $this->signed_in;
}
// login method
public function login($user){
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
// log out method
public function logout(){
unset($this->$_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
// check the login method
private function check_the_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
}else{
unset($this->user_id);
$this->signed_in = false;
}
}
}
$session = new Session();
Seems that your logout method has error. Replace this line unset($this->$_SESSION['user_id']); to unset($_SESSION['user_id']); and try
public function logout(){
unset($this->$_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
Should be like below
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
Try using a POST request in your form. I had this problem using a redirect after a get request from. Doing two get requests, one from the form, and one from the redirect causes an infinite loop.
So I made a registration page and i'm also using sessions to flash messages.
The session is called 'flash' and I made an abstraction class for sessions to make it easier.
This is my Session class:
public static function exists($name)
{
return (isset($_SESSION[$name]) ? (true) : (false));
}
public static function set($name, $value)
{
return $_SESSION[$name] = $value;
}
public static function delete($name)
{
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function get($name)
{
if(self::exists($name)) {
return $_SESSION[$name];
}
return '';
}
public static function hasFlash()
{
return (Session::exists('flash') ? (true) : (false));
}
public static function addFlash($message)
{
if(Session::exists('flash'))
{
$msgArray = (Array) Session::get('flash');
array_push($msgArray, $message);
Session::set('flash', (Array) $msgArray);
}
else
{
$msgArray = array();
array_push($msgArray, $message);
Session::set('flash', (Array) $msgArray);
}
}
public static function flash($message = null)
{
if(self::hasFlash()) {
$msgArray = (Array) Session::get('flash');
Session::delete('flash');
foreach($msgArray as $message) {
echo $message . "<br>";
}
}
return '';
}
And this is my registration page:
$hasError = false;
$username = Functions::escape(Input::get('user'));
$password = Functions::escape(Input::get('password'));
$email = Functions::escape(Input::get('email'));
$nick = Functions::escape(Input::get('nick'));
if(User::userExists($username, $db)) {
Session::addFlash("User $username is taken, try another one.");
$hasError = true;
}
if(User::emailExists($email, $db)) {
Session::addFlash("Email $email is taken, try another one.");
$hasError = true;
}
if(!$hasError)
{
User::addUser($username, $email, $password, $nick, $db);
Session::addFlash("You have successfully registered.");
Session::addFlash("You can now login with $username.");
Functions::location("index.php");
}
That's the code i'm using to display the flash messages:
<?php if(Session::hasFlash()) : ?>
<div class="form-group">
<?php Session::flash(); ?>
</div>
<?php endif; ?>
However it only works on the registration page for instance when a user types in a username/email that is taken, the code above will show the message though when I register the user and send him to the index page, the 2 success messages won't show up. I do have session_start at the top of the page.
The issues seemed to resolve by adding the following:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
I'm basically trying a session control. If the user is logged in, it's ok to move on. But if he's not logged in, then it will show a log-in screen and then die. However, when I use die or exit in the constructor, it does not show the log-in screen; it immediately dies. The code is as following:
private $username = null;
private $mongoid = null;
private $neoid = null;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
die;
}
}
It shows the log-in page if die is not written there, but with die, it does not show. Why do I want to use die? Because if I don't use, it moves on the index function and I don't want it to execute index function if the user is not logged in.
What is wrong here? What should I use to stop executing?
CodeIgniter does not instantly output the view when you load it with $this->load->view();, it puts the output of the view to the output buffer instead and after everything is loaded it flushes the whole output to the user. With that said, the problem you are seeing is that it buffers the output, then it dies without flushing it.
die is really bad and should not be used outside debugging, you should better use something like a variable switch. If it's only for the controllers scope, then you can make a
private $show_everything_else = true;
In the constructor:
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->show_everything_else = false;
}
In any of the controller's methods:
if($this->show_everything_else) {
// ...
}
In any case, this solution is a quick fix and there are much better possibilities how to do this, but all of them require a different approach.
You can have a method and call it in constructor:
function __construct() {
parent::__construct();
$this->_is_logged_in();
}
and the method should look like this:
function _is_logged_in() {
$is_logged_in = $this->session->userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true) {
redirect('login');
die();
}
}
And, of course, you should have controller for login, which can look like this:
<?php
class Login extends CI_Controller {
function index() {
$this->load->view('LOGIN-VIEW');
}
function validate() {
$this->load->model('login_model');
$data = $this->login_model->validate();
if ($data != false) {
$data['is_logged_in'] = true;
$this->session->set_userdata($data);
redirect('MAIN-CONTROLLER-AFTER-LOGIN');
}
else {
$this->index();
}
}
function logout() {
$this->session->sess_destroy();
$this->index();
}
}
This what i posted, also preserve sessions in database.
Login model can be as primitive as this:
class Login_model extends CI_Model {
function validate() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('users');
if($query->num_rows == 1) {
$data = $query->row_array();
return $data;
} else {
return false;
}
}
The Controller class will automatically run the index() function. So, to make it work, you must return the index() if the login check in construct is failed. Here what you can do:
private $username = null;
private $mongoid = null;
private $neoid = null;
private $no_login = false;
public function __construct(){
parent::__construct();
// session to global
$this->username = $this->session->userdata( 'username');
$this->mongoid = $this->session->userdata( 'mongoid');
$this->neoid = $this->session->userdata( 'neoid');
// check if user is logged in
if( $this->username == "" || empty( $this->username)){
$this->load->view( 'access/login');
$this->no_login = true;
}
}
function index(){
if($this->no_login) return;
// another statement if login success.....
}