Im wondering why my sessions are not being set when they are in the "login()" function. If i set sessions in the constructor or in the find() function, they are properly set, but if i put them in the login() function, they are not being set. Can anyone answer me why? Session start() is being loaded in all files because of autload, so that shouldent be a problem.
login.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '/home/1/u/someplace/www/Core/init.php';
if(Input::exists()){
if(Token::validate(Input::get('token'))){
$validate = new validator;
$passed = $validate->validate($_POST, array('email' => array('required' => 'true'), 'password' => array('required' => 'true')));
if ($passed) {
$user = new users(Input::get('username'));
if($user->login(Input::get('password')));{
redirect::to("http://www.someplace.info/Includes/index.php");
}
}else{
echo "not passed";
}
}
}
?>
<html>
<header></header>
<body>
<form action="" method="post">
<input name="username" value="<?php echo Input::get('email');?>">
<input name="password" value="<?php echo Input::get('password')?>">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>" >
<input type="submit" value="Login">
</form>
</body>
</html>
Users.php :
<?php
class users{
private $_db;
private $_data = array();
private $_sessionName;
private $_cookieName;
private $_isLoggedIn;
private $_link;
function __construct($user = null){
$this->_db = Database::getDBI();
$this->_cookieName = Config::get('cookie:cookie_name');
$this->_sessionName = Config::get('session:session_name');
if (Session::exists($this->_sessionName) && $user == null) {
$user = Session::get($this->_sessionName); //session = name[user], value = user_id
//sessions can be put here.
if($this->find($user)){
$this->_isLoggedIn = true;
} elseif(!$this->_link == "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]") {
redirect::to("http://www.ulrikbf.info/includes/login.php");
}
} else {
$this->find($user);
}
}
public function create($table,$field,$values = array()){
if (!$this->_db->insert($table,$field,$values)) {
return false;
}
}
public function find($user = null){
//sessions can be put here.
switch ($user) {
case is_numeric($user):
$this->_data = $this->_db->get('users', array('user_id','=',$user));
break;
case $user == null:
$this->_data = $this->_db->get('users', array('email','=',session::get(config::get('session::session_name'))));
break;
default:
$data = $this->_data = $this->_db->get('users', array('email','=', $user));
$datafirst = $data->first();
if ($user == $datafirst->email) {
$this->_data = $datafirst;
}
break;
return $this->_data;
}
}
public function login($user_password = null){
$password = hash::make($user_password, $this->_data->salt);
$passwordHash = $this->_data->password;
if ($passwordHash == $password ) {
$hashSession = hash::unique();
session::put('hash', $hashSession); //not working
session::put($this->_sessionName,$this->data()->user_id); //not working.
$this->_db->insert('sessions','user_id, hash', array(
$this->_data->user_id, $hashSession));
return true;
}
return false;
}
public function data(){
return $this->_data;
}
public function isLoggedIn(){
return $this->_isLoggedIn;
}
}
index.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '/home/1/u/someplace/www/Core/init.php';
$user = new users();
print_r($_SESSION);
if($user->isLoggedIn()){
echo "Great";
} else {
echo "Not so great";
}
?>
init.php:
session_start();
//Standard PHP Library(spl)..
spl_autoload_register(function($class) {
require_once '/home/1/u/someplace/www/Classes/' . $class . '.php';
});
session.php:
<?php
class session {
public static function put($name,$value){
return $_SESSION[$name] = $value;
}
}
You need to start session in each file
session_start();
Related
I am trying to get users details from the database and put it in session so that it can be used in the view. I have tried all I can but I keep getting error. Undefined Variable Email.
MODEL:
function login($username, $password)
{
$this->db->select('authTbl.id, authTbl.password, authTbl.username, authTbl.email, authTbl.mobile');
$this->db->from('users as authTbl');
$this->db->where('authTbl.username', $username);
$this->db->where('authTbl.isDeleted', 0);
$query = $this->db->get();
$user = $query->result();
if(!empty($user)){
if(verifyHashedPassword($password, $user[0]->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
CONTROLLER:
function isLoggedIn()
{
$isLoggedIn = $this->session->userdata('isLoggedIn');
$data['title'] = 'Login';
if(!isset($isLoggedIn) || $isLoggedIn != TRUE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
redirect('posts');
}
}
/**
* This function used to logged in user
*/
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Login';
$this->form_validation->set_rules('username', 'Username', 'required|max_length[128]|trim');
//$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]|');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->user_model->login($username, $password);
if(count($result) > 0)
{
foreach ($result as $res)
{
$sessionArray = array('id'=>$res->id,
'username'=>$res->username,
'email'=>$res->email,
'mobile'=>$res->mobile,
'isLoggedIn' => TRUE
);
$this->session->set_userdata($sessionArray);
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
}
}
else
{
$this->session->set_flashdata('login_fail', 'Email or password mismatch');
redirect('users/login');
}
}
}
VIEW:
<?php echo $email; ?>
You are creating the session for user information
Try to fetch the session data :
echo $this->session->userdata('email');
or trying to pass the data in views $data
$email will not work because writing $email means ordinary variable but in your case you have to write like :
<?php echo $this->session->userdata('email'); ?>
If You are using flashdata, then You can get it using below code:
Controller
if (empty($this->session->userdata('UserID'))) {
$this->session->set_flashdata('flash_data', 'You don\'t have access!');
$this->load->view("initialHeader");
$this->load->view("login");
redirect('Login');
}
View
<?php if(!empty($this->session->flashdata('flash_data'))) {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('flash_data'); ?>
</div>
<?php } ?>
If You are using tmp data as a session, please refer below code:
Controller
<?php
if (!empty($data)) {
$this->session->set_userdata('permission_error_msg', $data);
$this->session->mark_as_temp('permission_error_msg', 10); // For 10 Seconds
$this->load->view('dashboard', array($title, $data));
} ?>
View
<?php if ($this->session->tempdata('permission_error_msg')) { ?>
<b class="login_error_msg"><?php
if (!empty($this->session->tempdata('permission_error_msg'))) {
echo $this->session->tempdata('permission_error_msg');
}
?></b>
<?php } ?>
Thank You.
my validations are working ok but after that userid and password results empty in model fit_reg_model and it results into authentication failed.please help me out.
this is my code :
model fit_reg_model
`
class Ftg_reg_model extends CI_Model {
public function log_valid( $userid, $password )
{
$this->db->select("regID,loginCode");
$whereCondition = $array = array('regID' =>$userid,'loginCode'=>$password);
$this->db->where($whereCondition);
$this->db->from('fit_1login');
$query = $this->db->get();
////////////////////////////////checking values////////////////////
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
if( $query->num_rows() )
{
echo"<pre>";
print_r ($query->result()); exit;
return $query->row()->countID;
//return TRUE;
}
else
{
return FALSE;
}
}
}
contrller fit_ci
` public function fit_loguser()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('uname','User Id','required|valid_email|valid_emails|trim');
$this->form_validation->set_rules('password','Password','required|trim');
$this->form_validation->set_error_delimiters("","");
if($this->form_validation->run() )
{
$userid = $this->input->post('uname');
$password = $this->input->post('password');
//////////////////////////////////////loding model////////////////
$this->load->model('ftg_reg_model');
//echo $userid , $password;
if( $this->ftg_reg_model->log_valid('$userid','$password')== True )
{
//$this->load->view('fitasy/fit_userprofile');
$this->load->library('session');
$this->session->set_userdata('id',$id);
echo "Successful loged";
}
else
{
echo "Authentication failed";
}
}
else
{
$data['title'] = 'Fit';
$this->load->helper('form');
$this->load->view('fit/index.php',$data);
}
}
`
view fit_loguser
`
Login here to add items to your Cart
'form-horizontal'])?>
<?php echo form_error('uname'); ?>
<?php echo form_input(['name'=>'uname','class'=>'form-control','placeholder'=>'Username','value'=>set_value('uname')])?><br>
<?php echo form_error('password'); ?>
<?php echo form_password(['name'=>'password','class'=>'form-control','placeholder'=>'Password'])?><br>
<?php echo form_submit(['name'=>'logsubmit','class'=>'btn btn-default','value'=>'Proceed','type'=>'submit'])?>
<?php echo form_close()?><!-------------form close-------------------------------------->
</div>`
Try to remove
$this->db->select("regID,loginCode");
In your model to see what's happening
I have this login form based on "token" validation while everything seems to working fine it always echo "Front Page Rather than "Member Access".
I have the error reporting on.
<body>
<?php
if (isset($_POST['login'])) {
include('test.php');
$login = new login();
if($login->isLoggedIn())
header('location: home.php');
else
$login->showErrors();
}
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true));
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr><td>Username:</td><td><input type="text" name="username" /></td></td>
<tr><td>Password:</td><td><input type="password" name="password" /></td></td>
</table>
<input type="hidden" name="token" value="<?php echo "$token"; ?>" />
<input type="submit" name="login" value="Login" />
</body>
And, test php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
class login
{
if(isset($_POST['login'])){
private $_id;
private $_username;
private $_password;
private $_passwordmd5;
}
private $_errors;
private $_access;
private $_login;
private $_token;
public function __construct()
{
$this->_errors = array();
$this->_login = isset($_POST['login'])? 1 : 0;
$this->_access = 0;
$this->_token = $_POST['token'];
$this->_id = 0;
$this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username'];
$this->_password = ($this->_login)? $this->filter($_POST['password']) : '';
$this->_passwordmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->_login)? $this->verifyPost() : $this->verifySession();
return $this->_access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->isTokenValid())
throw new exception('Invalid Form Token');
if(!$this->isDataValid())
throw new exception('Invalid Username & Password Criteria');
if(!$this->verifyDatabase())
throw new exception('Not able to connect');
$this->_access=1;
$this->registerSession();
}
catch (exception $e)
{
$this->_errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->_access = 1;
}
public function verifyDatabase()
{
// Database Connection
$con=mysqli_connect("localhost","","");
if (!$con) { die("Database connection failed: " . mysqli_error($con));}
$db_select=mysqli_select_db($con, "");
if (!$db_select) { die("Database selection failed: " . mysqli_error($con));}
$data = "SELECT id FROM users WHERE username='$this->_username' AND password='$this->_passwordmd5'";
if (mysqli_num_rows($con, $data) == 0)
{
list($this->_id) = #array_values(mysqli_fetch_assoc($data));
return true;
}
else
{ return false; }
}
public function isDataValid()
{
return (preg_match('/^[a-zA-Z0-9](5-15)$/',$this->_username) && preg_match('/^[a-zA-Z0-9](5-20)$/',$this->_password))? 0 : 1;
}
public function isTokenValid()
{
return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 0 : 1;
}
public function registerSession()
{
$_SESSION['ID'] = $this->_id;
$_SESSION['username'] = $this->_username;
$_SESSION['password'] = $this->_passwordmd5;
}
public function sessionExist()
{
return (!isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0;
}
public function showErrors()
{
echo "<h3>Errors</h3>";
foreach($this->_errors as $key=>$value)
echo $value."<br>";
}
}
?>
Home php:
session_start();
include('test.php');
$login = new login();
if($login->isLoggedIn())
echo "Member Access";
else echo
"Front Page";
Looking someone willing to help.
Your function isTokenValid is returning the opposite of what it should. Essentially you have:
return $invalidToken ? 1 : 0;
Returning 1 if the token doesn't match. Reverse it to ? 0 : 1; or simplify and return boolean:
return isset($_SESSION['token']) && $this->_token === $_SESSION['token'];
I've created a login class for my web app and it does work, but now I've created that infamous "keep me logged in" - checkbox and don't get it to work. Here's my class for login:
<?php
error_reporting(E_ALL ^ E_NOTICE);
class Login {
private $error;
private $connect;
private $email;
private $password;
public $row;
public function __construct(PDO $connect) {
$this->connect = $connect;
$this->error = array();
$this->row = $row;
}
public function doLogin() {
$this->email = htmlspecialchars($_POST['email']);
$this->password = htmlspecialchars($_POST['password']);
$this->rememberme = $_POST['rememberme'];
if($this->validateData()) {
$this->fetchInfo();
}
return count($this->error) ? 0 : 1;
}
public function validateData() {
if(empty($this->email) || empty($this->password)) {
$this->error[] = "Täyttämättömiä kenttiä";
} else {
return count($this->error) ? 0 : 1;
}
}
public function fetchInfo() {
$query = "SELECT * FROM users WHERE email = :email AND activation_token IS NULL";
$stmt = $this->connect->prepare($query);
$stmt->execute(array(
':email' => $this->email,
));
if($stmt->rowCount() == 0) {
$this->error[] = "Väärä käyttäjätunnus tai salasana";
return 0;
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['email'] = $row['email'];
$_SESSION['name'] = $row['name'];
$_SESSION['profilepic'] = $row['profilepic'];
if(isset($this->rememberme)) {
setcookie("loggedin", "yes", time() + 25200);
}
}
if (Register::cryptPass($this->password) != $row['password']) {
$this->error[] = "Virheelliset kirjautumistiedot";
} else {
return true;
}
return count($this->error) ? 0 : 1;
}
public function displayErrors() {
if(!count($this->error)) return;
echo "<div class='login_error'>";
foreach($this->error as $key=>$value) {
echo "<p>".$value."</p>";
}
echo "</div>";
}
public function doLogout() {
session_destroy();
}
}
?>
And here's a small part of my code from my another file where I'm checking if the session or cookie is set:
<?php
if (isset($_SESSION['email']) || isset($_COOKIE['loggedin'])) {
?>
<div id="header_container_isloggedin">
<div class="container_12">
<header id="header">
<div class="grid-12">
<ul id="menu">
<li class="profile-name">
<a href="profile.php?id=<?php echo $_SESSION['user_id']; ?>">
<span class="header_username">
<img src="images/thumbnails/<?php echo $_SESSION['profilepic']; ?>"
class="profile_evensmaller"/>
<span class="header_name"><?php echo $_SESSION['name']; ?></span></span></a>
</li>
</ul>
<?php } ?>
The problem is that everytime the cookie is set, it doesn't display my profile picture or name since they've saved inside of $_SESSION variable. So how should I approach this and get this to work. I know that right now it's not the safest method, since I'm not generating any hashes for that cookie, but right now the only thing I'm interested in, is to get this one to work.
I am doing the Lynda.com learning PHP 2 videos and have run into a problem, in that the instructor seems to have neglected to tell us one of the steps he does in the video. I have uploaded the relevant video here http://www.youtube.com/watch?v=fFKgAa7RAjo but will also describe the problem. At 6:40 of the video, after logging in to our application, he arrives at public/admin/index.php which has two links on it. one link allows him to "view log file" which takes him to public/admin/logfile.php and the other link allows him to log out. He doesn't tell us how to make these links. I can obviously make a link to view logfile
View Logfile
but I don't know how to make the link that will log me out, because that will obviously involve some PHP.
I have included below the login.php file, the index.php file (it's redirected to index.php after logging in) and the functions.php file. Do you know how I would logout from this?
This is the login.php file
<?php
require_once("../../includes/initialize.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} logged in.");
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.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Functions.php
<?php
function strip_zeros_from_date( $marked_string=""){
//first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location= NULL) {
if($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message=""){
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)){
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
function include_layout_template($template=""){
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
function log_action($action, $message=""){
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { //apppend
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle,$content);
fclose($handle);
if($new) {chmod($logfile, 0755); }
} else {
echo "Could not open log file for writing.";
}
}
?>
Index.php
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Menu</h2>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Update
Initialize.php
<?php
//Directory_separator is a PHP pre-defined constant
// (\ for windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'c263430'.DS.'quoralist.com');
// define('SITE_ROOT', realpath(dirname(__FILE__).'/../'));
//echo SITE_ROOT."<br/>";
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// die(LIB_PATH);
//echo LIB_PATH."<br/>";
require_once(LIB_PATH.DS."config.php");
require_once(LIB_PATH.DS."functions.php");
require_once(LIB_PATH.DS."session.php");
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."database_object.php");
require_once(LIB_PATH.DS."user.php");
//echo("You die here");
?>
User.php
<?php
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject{
protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="",$password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>
Session.php
<?php
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();
?>
<?php
session_start();
session_destroy();
?>
That should destroy all variables stored in the session. It is really primitive logging out, but it should work. After you do that just redirect to "index.php" or whatever page you want.