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.
Related
SO i have been trying with a php project and everything is working fine.Except a bit extra.
Login page redirects to Dashboard even with incorrect details .So basically login is bypassed regardless the login details. Also By putting "sitename/dashboard" directly also bypasses the login. Below Are my Code.
1.index(login page)
<?php
require('inc/dbPlayer.php');
require('inc/sessionManager.php');
$msg="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["btnLogin"])) {
$db = new \dbPlayer\dbPlayer();
$msg = $db->open();
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>HMS</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel-body">
<form name="login" action="index.php" accept-charset="utf-8" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail/Login ID" name="email" type="text" autofocus required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="" required>
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
Forget Password
<label id="loginMsg" class="red"><?php echo $msg ?></label>
</div>
<button type="submit" name="btnLogin" class="btn btn-lg btn-success btn-block"><i class="glyphicon glyphicon-log-in"></i> Login</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
2.dbplayer
<?php
namespace dbPlayer;
class dbPlayer {
private $db_host="localhost";
private $db_name="hms";
private $db_user="root";
private $db_pass="";
protected $con;
public function open(){
$con = mysql_connect($this->db_host,$this->db_user,$this->db_pass);
if($con)
{
$dbSelect = mysql_select_db($this->db_name);
if($dbSelect)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function close()
{
$res=mysql_close($this->con);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
public function insertData($table,$data)
{
$keys = "`" . implode("`, `", array_keys($data)) . "`";
$values = "'" . implode("', '", $data) . "'";
//var_dump("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
mysql_query("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
return mysql_insert_id().mysql_error();
}
public function registration($query,$query2)
{
$res=mysql_query($query);
if($res)
{
$res=mysql_query($query2);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function getData($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't get data ".mysql_error();
}
else
{
return $res;
}
}
public function update($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't update data ".mysql_error();
}
else
{
return "true";
}
}
public function updateData($table,$conColumn,$conValue,$data)
{
$updates=array();
if (count($data) > 0) {
foreach ($data as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
}
$implodeArray = implode(', ', $updates);
$query ="UPDATE ".$table." SET ".$implodeArray." WHERE ".$conColumn."='".$conValue."'";
//var_dump($query);
$res = mysql_query($query);
if(!$res)
{
return "Can't Update data ".mysql_error();
}
else
{
return "true";
}
}
public function delete($query)
{
$res = mysql_query($query);
// var_dump($query);
if(!$res)
{
return "Can't delete data ".mysql_error();
}
else
{
return "true";
}
}
public function getAutoId($prefix)
{
$uId="";
$q = "select number from auto_id where prefix='".$prefix."';";
$result = $this->getData($q);
$userId=array();
while($row = mysql_fetch_assoc($result))
{
array_push($userId,$row['number']);
}
// var_dump($UserId);
if(strlen($userId[0])>=1)
{
$uId=$prefix."00".$userId[0];
}
elseif(strlen($userId[0])==2)
{
$uId=$prefix."0".$userId[0];
}
else
{
$uId=$prefix.$userId[0];
}
array_push($userId,$uId);
return $userId;
}
public function updateAutoId($value,$prefix)
{
$id =intval($value)+1;
$query="UPDATE auto_id set number=".$id." where prefix='".$prefix."';";
return $this->update($query);
}
public function execNonQuery($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return "true";
}
}
public function execDataTable($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return $res;
}
}
}
3.Session manager
<?php
namespace sessionManager;
class sessionManager {
public function Set($key,$value)
{
$_SESSION[$key] = $value;
// $_SESSION['start'] = time();
// $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
public function Get($key)
{
// session_start();
if(isset($_SESSION[$key])) {
return $_SESSION[$key];
}
else
{
return null;
}
}
public function isExpired()
{
//session_start();
$now = time();
if ($now > $_SESSION['expire']) {
session_unset();
session_destroy();
return true;
}
else
{
return false;
}
}
public function remove($key)
{
//session_start();
unset($_SESSION[$key]);
}
public function start()
{
session_start();
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
}
A few hints:
require values should not be in brackets.
you should NOT be using mysql_ functions, this library is now CEASED and unavailable in PHP 7. Get up to date to 2012 and use mysqli_ or PDO. (Why?)
You should be using PHP 7. As a minimum. (Why?)
Do NOT use md5 for hashing passwords. Use PHP's built in password_hash() function(s). (How?)
STOP outputting errors to screen (aka return mysql_error();). You should be sending errors to an error log (error_log(print_r(mysql_error(),true));) so the public can't see the details of the error.
Read your PHP Error Log. What does it say?
Use Prepared Statements on your database interactions. ([How?(https://phpdelusions.net/mysqli))
Header("Location: ... "); functions should always be immediately followed by exit;/die();
NEVER trust user input. Even if the user tells you it's harmless. (Why?)
Read your PHP Error Log. What does it say?
Your classes should probably have class __constuct() functions. (why?)
You can use Boolean Values instead of strings; use return true; instead of return "true";
You STILL should NOT be using mysql_ functions, Why are you still using them? Stop reading this and update your codebase! Use mysqli_ or PDO. (Why?)
Learn the differences between the different PHP Comparison Operators. And apply what you learn to your code.
Use the PHP Manual to find out and use the multitude of functions available in PHP.
Please get in touch with me if you wish to purchase a copy of PHP 6 (rated 4.5/5 stars on TripAdvisor).
You have a lot of reading to do, and a lot to learn. I would say good luck, but you don't need any luck, you need to read and commit yourself to learning how to use PHP properly.
Have fun.
You need to apply a condition whether you have record in database or not. If not then you need to bypass to login page. Change this code as below:
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
if (mysql_num_rows($result) > 0) { // means user is logged in
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
But I will suggest you to use PDO as mysql is deprecated already. Also your code is widely open for SQL injection as well so read about it as well. Hope it helps you but make your code reliable.
I'm trying to print userdata from another table with session. The table with the session is "userlogin" while the table with the data is "userinfo"
Here's what I've done so far
Controller
public function index()
{
if ( $this->session->userdata('logged_in') )
{
$session_data = $this->session->userdata('userinfo');
$id = $session_data['id'];
$this->load->model('Userdata_model');
$result = $this->Userdata_model->get_user_data3($id);
if($result==0)
{
echo 'No user Found';
}
else
{
$data['id']=$result;
$this->load->view("userdata_view", $data);
}
}
}
Model
public function get_user_data3($id)
{
if (isset($this->session->userdata['logged_in'])) {
$userid = ($this->session->userdata['logged_in']['id']);
} else {
header("location: http://localhost/test");
}
$query = $this->db->query("SELECT * FROM userinfo WHERE id='$id'");
foreach ($query->result_array() as $row)
{
echo $row['fName'];
echo $row['phone'];
}
}
View
<?php foreach ( $query->result_array as $new_user )
{
?>
<h4>Your name: <?php echo $new_user['fName'] ?> </h4>
<?php
}
?>
change function in controller :
public function index()
{
if ( $this->session->userdata('logged_in') )
{
$session_data = $this->session->userdata('userinfo');
$id = $session_data['id'];
$this->load->model('Userdata_model');
$data['result'] = $this->Userdata_model->get_user_data3($id);
$this->load->view("userdata_view", $data);
}
}
change model function like:
public function get_user_data3($id)
{
$query = $this->db->query("SELECT * FROM userinfo WHERE id='$id'");
return $query;
}
and view :
<?php if($result->num_rows() == 0){
echo 'No user found';
}
else {
foreach ( $result->result_array() as $new_user ){ ?>
<h4>Your name: <?php echo $new_user['fName'] ?> </h4>
<?php }
}
?>
My login of admin panel and member panel both works fine on local server, But on Live server member panel doesn't work. As admin and member panel both use same connection file so it means connection file works fine. More over when we fill wrong user or password it says
Invalid User or Password
But when we login with correct user or password it returns back with no indication of error.
My login file upper php part is:
<?php
include_once("../init.php");
$msg='';
?>
<?php
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
My header file main.php is
<?php
include_once("../init.php");
validation_check($_SESSION['SID'],MEM_HOME_ADMIN);
$msg='';
$dir ='../'.USER_PIC;
$sId = $_SESSION['SID'];
?>
Session is started from another file called function.php
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
Moreover I have created user id by words and time like LH1450429882 and column is verture type. I think this has no effect on login.
I think main errors come from function.php Sorry for a long code, but I tried to cover all parts of coding.
I am struggling with this code from a week. Thanks in advance for help.
This is probably a bug that error_reporting will show off. Always use it in development mode, to catch some carelessness errors and ensure the code's clarity.
ini_set('display_errors',1);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
By implementing code ini_set('display_errors',1); error_reporting(E_ERROR | E_WARNING | E_PARSE); I got the error of header ploblem on line 6 in login php I have removed ?> and
Now my working code in login.php is
<?php
include_once("../init.php");
$msg='';
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
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 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.