Recently, I have been having a problem with my sessions, and corresponding session variables.
The problem, is that, when I POST sessions1.php, the session variable seems to work, and gets carried over into sessions2.php.
But, when the link to go to sessions3.php is clicked, the session variable doesn't seem to be set, when in sessions3.php. Thus, returning code from the "else" block, within the "if/else" conditional.
Something similar seems to be happening when I use either a database, or /tmp file setup, for storing data.
In the database example, the session is written to the sessions table. However, when I click the link, going from sessions2.php, which takes me to sessions3.php, the session variable doesn't seem to be set. And, when I click the "logout" button, within sessions3.php, the link takes me back to sessions1.php, which is what is supposed to happen. However, when I check the database (or at least refresh the sessions table), the session is not removed, or destroyed, according to what should be happening in line with the SessionHandler class.
Furthermore, still with the database example: when I submit sessions1.php, and am taken to sessions2.php, the right session row is created within the sessions table. However, when I click on the link that takes me to sessions3.php, another row is created, within the sessions table: this time, without any data, in the data column.
On the other hand, in an test without a database, thus, resorting to using the file-system instead: after submitting sessions1.php, the file appears in the /tmp directory. However, on inspection, that file remains empty. Please, also bear in mind that, when using a simple file-system example, the "SessionHandler", and db connection, code is not present within the files.
Any possible solutions?.
I am using PHP7, Apache 2.4, and MySQL 5.6.27. And, I am wondering whether my config settings (php.ini, and/or httpd) may have anything to do with the problem (since, even without a database, the interactions between sessions2.php, and sessions3.php produce somewhat similar results (session variable not set, by the time I get to sessions3.php)).
THE CODE:
sessions1.php(below)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<form method="post" action="sessions2.php">
<p>
<label for="name">Enter your first name: </label>
<input type="text" name="name" id="name">
</p>
<p>
<input type="submit" name="submit" value="Submit">
</p>
</form>
</body>
</html>
session2.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['name'])) {
if (!empty($_POST['name'])) {
$_SESSION['name'] = htmlentities($_POST['name']);
} else {
$_SESSION['name'] = 'Nobody Here!';
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello, <?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
} else {
echo 'stranger';
}
?>.</p>
<p>Go to page 3</p>
</body>
</html>
session3.php (below)
<?php
use SomeNamespace\Sessions\SessionHandler;
require_once('/databases/dbConnect.php');
require_once('/classes/Sessions/SessionHandler.php');
$handler = new SessionHandler($db);
session_set_save_handler($handler);
session_start();
if (isset($_POST['logout'])) {
$_SESSION = [];
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 86400, $params['path'],
$params['domain'], $params['secure'], $params['httponly']);
session_destroy();
header('Location: sessions1.php');
exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session Test</title>
</head>
<body>
<p>Hello<?php
if (isset($_SESSION['name'])) {
echo ' again, ' . $_SESSION['name'];
} else {
echo ', Nobody!';
}
?>.</p>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<p><input type="submit" name="logout" value="Log Out"></p>
</form>
</body>
</html>
SessionHandler.php (below) The session handler class.
namespace SomeNamespace\Sessions;
class SessionHandler implements \SessionHandlerInterface
{
protected $db;
protected $useTransactions;
protected $expiry;
protected $table_sess = 'sessions';
protected $col_sid = 'sessionID';
protected $col_expiry = 'expiry';
protected $col_data = 'data';
protected $unlockStatements = [];
protected $collectGarbage = false;
public function __construct(\PDO $db, $useTransactions = true)
{
$this->db = $db;
if ($this->db->getAttribute(\PDO::ATTR_ERRMODE) !== \PDO::ERRMODE_EXCEPTION) {
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
$this->useTransactions = $useTransactions;
$this->expiry = time() + (int) ini_get('session.gc_maxlifetime');
}
public function open($save_path, $name)
{
return true;
}
public function read($session_id)
{
try {
if ($this->useTransactions) {
$this->db->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
$this->db->beginTransaction();
} else {
$this->unlockStatements[] = $this->getLock($session_id);
}
$sql = "SELECT $this->col_expiry, $this->col_data
FROM $this->table_sess WHERE $this->col_sid = :sessionID";
if ($this->useTransactions) {
$sql .= ' FOR UPDATE';
}
$selectStmt = $this->db->prepare($sql);
$selectStmt->bindParam(':sessionID', $session_id);
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
if ($results[$this->col_expiry] < time()) {
return '';
}
return $results[$this->col_data];
}
if ($this->useTransactions) {
$this->initializeRecord($selectStmt);
}
return '';
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
}
public function write($session_id, $data)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid,
$this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)
ON DUPLICATE KEY UPDATE
$this->col_expiry = :expiry,
$this->col_data = :data";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$stmt->bindParam(':data', $data);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
return true;
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
public function close()
{
if ($this->db->inTransaction()) {
$this->db->commit();
} elseif ($this->unlockStatements) {
while ($unlockStmt = array_shift($this->unlockStatements)) {
$unlockStmt->execute();
}
}
if ($this->collectGarbage) {
$sql = "DELETE FROM $this->table_sess WHERE $this->col_expiry < :time";
$stmt = $this->db->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->execute();
$this->collectGarbage = false;
}
return true;
}
public function destroy($session_id)
{
$sql = "DELETE FROM $this->table_sess WHERE $this->col_sid = :sessionID";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':sessionID', $session_id);
$stmt->execute();
} catch (\PDOException $e) {
if ($this->db->inTransaction()) {
$this->db->rollBack();
}
throw $e;
}
return true;
}
public function gc($maxlifetime)
{
$this->collectGarbage = true;
return true;
}
protected function getLock($session_id)
{
$stmt = $this->db->prepare('SELECT GET_LOCK(:key, 50)');
$stmt->bindValue(':key', $session_id);
$stmt->execute();
$releaseStmt = $this->db->prepare('DO RELEASE_LOCK(:key)');
$releaseStmt->bindValue(':key', $session_id);
return $releaseStmt;
}
protected function initializeRecord(\PDOStatement $selectStmt)
{
try {
$sql = "INSERT INTO $this->table_sess ($this->col_sid, $this->col_expiry, $this->col_data)
VALUES (:sessionID, :expiry, :data)";
$insertStmt = $this->db->prepare($sql);
$insertStmt->bindParam(':sessionID', $session_id);
$insertStmt->bindParam(':expiry', $this->expiry, \PDO::PARAM_INT);
$insertStmt->bindValue(':data', '');
$insertStmt->execute();
return '';
} catch (\PDOException $e) {
if (0 === strpos($e->getCode(), '23')) {
$selectStmt->execute();
$results = $selectStmt->fetch(\PDO::FETCH_ASSOC);
if ($results) {
return $results[$this->col_data];
}
return '';
}
if ($this->db->inTransaction()) {
$this->db->rollback();
}
throw $e;
}
}
}
Related
I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:
/index.php - Uncaught Error: Call to a member function prepare() on
null in
/Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56
Stack trace:
0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)
1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')
2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')
3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line
56
Here is my code for index.php:
<?php
include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;
// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {
// TODO: filter input for the "box_file" and "description" parameters.
// Hint: filtering input for files means checking if the upload was successful
$upload_info=$_FILES["box_file"];
$upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
if ($upload_info['error']==UPLOAD_ERR_OK){
$upload_name=basename($upload_info["name"]);
$upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );
$sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
$params=array(
':user_id' => $current_user['id'],
':file_name'=> $upload_name,
':file_ext'=>$upload_ext,
':description'=>$upload_desc,
);
$result=exec_sql_query($db, $sql, $params);
if ($result){
$file_id=$db->lastInsertId("id");
$new_path="uploads/documents/$file_id.$upload_ext";
move_uploaded_file($upload_info["tmp_name"],$new_path);
}
}
// TODO: If the upload was successful, record the upload in the database
// and permanently store the uploaded file in the uploads directory.
// $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
// $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>
<body>
<h1>Fine Art Photography</h1>
<div id="content-wrap">
<?php
// If the user is logged in, let them upload files and view their uploaded files.
if ( is_user_logged_in() ) {
foreach ($messages as $message) {
echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>\n";
}
?>
<h2>Upload a File</h2>
<!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
<form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
<ul>
<li>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<label for="box_file">Upload File:</label>
<input id="box_file" type="file" name="box_file">
</li>
<li>
<label for="box_desc">Description:</label>
<textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
</li>
<li>
<button name="submit_upload" type="submit">Upload File</button>
</li>
</ul>
</form>
<?php
} else {
?>
<p><strong>You need to sign in before you can upload image.</strong></p>
<?php
include("includes/login.php");
}
?>
<!-- <h2>Saved Files</h2> -->
<h2>Categories</h2>
<h2>Photos</h2>
<div class="img">
<?php
$records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
if (count($records) > 0) {
foreach($records as $record) {
echo "<div class=\"content\">";
echo "<div class=\"block\">";
echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
"\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</body>
</html>
And here is my code for init.php:
<?php
// vvv DO NOT MODIFY/REMOVE vvv
// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
if (version_compare(phpversion(), '7.0', '<')) {
define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
echo VERSION_MESSAGE;
throw VERSION_MESSAGE;
}
}
check_php_version();
function config_php_errors()
{
ini_set('display_startup_errors', 1);
ini_set('display_errors', 0);
error_reporting(E_ALL);
}
config_php_errors();
// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
if (!file_exists($db_filename)) {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (file_exists($init_sql_filename)) {
$db_init_sql = file_get_contents($init_sql_filename);
try {
$result = $db->exec($db_init_sql);
if ($result) {
return $db;
}
} catch (PDOException $exception) {
// If we had an error, then the DB did not initialize properly,
// so let's delete it!
unlink($db_filename);
throw $exception;
}
} else {
unlink($db_filename);
}
} else {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
return null;
}
function exec_sql_query($db, $sql, $params = array())
{
$query = $db->prepare($sql);
if ($query and $query->execute($params)) {
return $query;
}
return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^
// You may place any of your code here.
// $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');
define('SESSION_COOKIE_DURATION', 60*60*1);
$session_messages = array();
function log_in($username, $password) {
global $db;
global $current_user;
global $session_messages;
if ( isset($username) && isset($password) ) {
// check if username exists in the database
$sql = "SELECT * FROM users WHERE username = :username;";
$params = array(
':username' => $username
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// There shouldn't be repetitive username.
$account = $records[0];
// Check if password is correct
if ( password_verify($password, $account['password']) ) {
// Create session
$session = session_create_id();
// Store session ID in database
$sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
$params = array(
':user_id' => $account['id'],
':session' => $session
);
$result = exec_sql_query($db, $sql, $params);
if ($result) {
// If result exists, session stored in DB
// Send this back to the user.
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
$current_user = $account;
return $current_user;
} else {
array_push($session_messages, "Log in failed. Something went wrong");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "No username or password given.");
}
$current_user = NULL;
return NULL;
}
function find_user($user_id) {
global $db;
$sql = "SELECT * FROM users WHERE id = :user_id;";
$params = array(
':user_id' => $user_id
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// users are unique, there should only be 1 record
return $records[0];
}
return NULL;
}
function find_session($session) {
global $db;
if (isset($session)) {
$sql = "SELECT * FROM sessions WHERE session = :session;";
$params = array(
':session' => $session
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// No repetitive sessions
return $records[0];
}
}
return NULL;
}
function session_login() {
global $db;
global $current_user;
if (isset($_COOKIE["session"])) {
$session = $_COOKIE["session"];
$session_record = find_session($session);
if ( isset($session_record) ) {
$current_user = find_user($session_record['user_id']);
// The session will last for 1 more hour
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
return $current_user;
}
}
$current_user = NULL;
return NULL;
}
function is_user_logged_in() {
global $current_user;
// if $current_user is not NULL, then a user is logged in.
return ($current_user != NULL);
}
function log_out() {
global $current_user;
// Remove the session from the cookie and fgo back in time to expire the session.
setcookie('session', '', time() - SESSION_COOKIE_DURATION);
$current_user = NULL;
}
// ---- Check for login, logout requests. Or check to keep the user logged in. ----
// Check if we should login the user
if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
log_in($username, $password);
} else {
// check if the user already logged in
session_login();
}
// Check if we should logout the user
if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
log_out();
}
?>
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 make a login form using function, Im using class and function in different file. Here my code.
Login Form
<?php
require_once("controller/ED_Setting.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Test</title>
</head>
<body>
<?php
if(isset($_REQUEST['failure']))
{
echo "User/Password Wrong";
}
?>
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">
<label>Email:</label>
<input type="text" name="username" />
<br />
<label>Password:</label>
<input type="password" name="password" />
<br />
<input type="submit" name="cmdlogin" value="Login" />
</form>
</body>
</html>
And the login Function I Call
<?php
require_once("ED_Setting.php");
class login
{
function index()
{
$db = new ED_Setting();
$db->connect();
if(isset($_REQUEST['cmdlogin']))
{
$rs = $db->select("SELECT * FROM tbl_user where username = '".$_REQUEST['username']."' and password= '".($_REQUEST['password'])."'");
$res = $db->getResult();
if($res)
{
header('location: http://blup2h.rf.gd');
}
else
{
header('location: http://localhost/project/index.php?failure');
}
}
}
}
?>
And the Setting Connection is like this
<?php
class ED_Setting
{
private $db_host = "localhost"; // Change as required
private $db_user = "root"; // Change as required
private $db_pass = ""; // Change as required
private $db_name = "db_pembukuan"; // Change as required
private $con = false; // Check to see if the connection is active
private $result = array(); // Any results from a query will be stored here
// Function to make connection to database
public function connect(){
if(!$this->con){
$myconn = #mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name); // mysql_connect() with variables defined at the start of Database class
if($myconn){
return true;
}else{
array_push($this->result,mysqli_error());
return false; // Problem connecting return FALSE
}
}else{
return true; // Connection has already been made return TRUE
}
}
// Function to disconnect from the database
public function disconnect(){
// If there is a connection to the database
if($this->con){
// We have found a connection, try to close it
if(#mysql_close()){
// We have successfully closed the connection, set the connection variable to false
$this->con = false;
// Return true tjat we have closed the connection
return true;
}else{
// We could not close the connection, return false
return false;
}
}
}
public function select($sql){
$query = #mysqli_query($sql);
// $this->myQuery = $sql; // Pass back the SQL
if($query){
// If the query returns >= 1 assign the number of rows to numResults
$this->numResults = mysqli_num_rows($query);
// Loop through the query results by the number of rows returned
for($i = 0; $i < $this->numResults; $i++){
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
// Sanitizes keys so only alphavalues are allowed
if(!is_int($key[$x])){
if(mysqli_num_rows($query) >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result = null;
}
}
}
}
return true; // Query was successful
}else{
array_push($this->result,mysqli_error());
return false; // No rows where returned
}
}
// Function to update and delete into the database
public function query($sql)
{
if($query = #mysql_query($sql)){
array_push($this->result,mysql_affected_rows());
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}
// Public function to return the data to the user
public function getResult(){
$val = $this->result;
$this->result = array();
return $val;
}
}
?>
But it did'nt work. Any answers please?
Probably the problem is "" using on form action attribute.
Use this line
<form action="<?php echo "/mvc/controller/login.php";?>" method="post">
Instead of
<form action=""<?php echo "/mvc/controller/login.php";?>"" method="post">
I have followin PHP code, it is where I defined my functions:
<?php
function emaili_pikkus($email){
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
$emaili_pikkus=True;
}
}
function parooli_pikkus($parool)
{
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
$parooli_pikkus=True;
}
}
function varasem_olemasolu($email)
{
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad WHERE e_mail = '$email'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
$varasem_olemasolu=True;
}
else
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
}
}
function paroolide_kattuvus($parool, $parool_uuesti)
{
if($parool==$parool_uuesti)
{
$paroolide_kattuvus=True;
}
else{
echo "Paroolid ei kattu.";
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Praks/templates/registreeritud.php'>";
}
}
?>
Then I have other PHP code where I call necessary functions(They are seperated, because I want to use my functions in other applications too):
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1($parool.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi','$perekonnanimi','$hashed_pwd','$salt')";
emaili_pikkus($email);
if ($emaili_pikkus=True){
parooli_pikkus($parool);
}
if ($parooli_pikkus=True){
varasem_olemasolu($email);
}
if ($varasem_olemasolu=True){
paroolide_kattuvus($parool, $parool_uuesti);
}
if ($paroolide_kattuvus=True){
NewUser();
}
?>
And then I have my HTML code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
init.funcs.php looks like that:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
include_once 'functions/survey.funcs.php';
?>
It all together should be a registration form and it worked before I made few changes. Before those changes I had my functions defined to work only for this registration form and they had no parameters needed. Also they were nested in each other. My question is how should I write my second PHP code, so it all would work. Right now it creates new user even if some previous condition are not True. It is a long question and I would be very thankful if someone answers me.
You have a lot of errors in your code:
Your functions aren't returning any value. Variables intitalized inside the function will not be available outside it. The best way is to return a boolean value and check that outside
The function definition:
function some_func($param1, $param2) {
if (some_condition) {
// If everything okay, return TRUE
return TRUE;
} else {
// It's not gonna work with this, so return FALSE
return FALSE;
}
}
Checking the return value:
if (some_func($foo, $bar)) {
// some_func returned TRUE, do further processing
}
With if($var = True), you're not actually checking if a variable is true or not. You're assigning it the boolean value True. You need to write if($var == True instead.
You're using the deprecated mysql_* functions. They're deprecated. Use MySQLi or PDO instead.
Okay, this may sound off-topic, but I want to know if someone have had similar experience and if they found the problem/solution.
Sorry this post has grown more like self try-and-error raportting, cause no one have answered. I have added status updates of problem solving in bottom of question.
For a moment the problem seems to be my database update query.
I'm developing PHP+MySQL website on netbeans 7.3. + XAMPP. Everything was working fine. No suddenly my log-in form (suppose to save some $_SESSION variables and redirect to page) is not working.
Strange thing is that when I debug with Netbeans + Xdebug all goes fine. Session variables are set and page forwarded correctly.
Question: Does someone faced similar problem? Has anyone idea what could be going wrong?
I only can suppose something in system is set differently when I run xdebug. (But the exact(?) same log-in was working fine few days ago).
I have tried lot of things (many many hours but most of them don't come to my mind now). I tried to move the page on remote server and same behavior continues.
(If you want more info ask and I'll edit.)
Hope someone has ideas!
EDIT: I think has something to do with my php-session variables. I realized that while Xdebug the site starts with empty php-session variables, so it does use/get same ones it normally has (?)
The code is creating sessions to database, but it does not get to the next step to set the php-session variables. (Check out the place in index.php marked as /* HERE IS THE PLACE */
Okay. HERE IS STRIPPED CODE (working with netbeans+xdebug, not alone):
index.php:
<?php
//Open PDO connection to MySQL server: $db_con
$db_connection = $_SERVER['DOCUMENT_ROOT'] . '/test-login/db.php';
require $db_connection;
session_start();
//******************************************************************************
//Helping functions
function convert_time_to_utc_date ($UNIX_timestamp) {
return gmdate("Y-m-d H:i:s", $UNIX_timestamp);
}
//******************************************************************************
// Function to authenticate user with username and password. returns FALSE if not authenticated and TRUE if successful authentication
function authenticate_username_password($db_con, $usernm, $passwd)
{
try {
$stmt = $db_con->prepare("SELECT id, hashed_pwd, COUNT(*) AS usercount FROM gui_users WHERE username=? AND not_in_use = 0 AND deleted = 0");
$stmt->execute(array($usernm));
if($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if($row['usercount'] == 1){
if(crypt($passwd, $row['hashed_pwd']) == $row['hashed_pwd']){
$user_id = $row['id'];
session_regenerate_id(true);
$new_session_id = session_id();
$remote = true;
$datenow = convert_time_to_utc_date(time());
$stmt = $db_con->prepare("INSERT INTO gui_sessions (session_id,user_id,starttime_UTC,lastused_UTC,remote) VALUES (?, ?, ?, ?, ?)");
$stmt->execute(array($new_session_id, $user_id, $datenow, $datenow, $remote));
return $user_id;
}
}
}
return FALSE;
} catch (PDOException $e) {
return FALSE;
}
}
//******************************************************************************
//Function to get user roles
function get_user_roles(PDO $db_con, $user_id)
{
try {
$stmt = $db_con->prepare("SELECT role_id, role_last FROM gui_users WHERE id = ?");
$stmt->execute(array($user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return array('max_role_id' => $row['role_id'], 'last_role_id' => $row['role_last']);
} catch (PDOException $e) {
return FALSE;
}
}
//******************************************************************************
// Function to handel sessions, log in and log out
function authenticate(PDO $db_con) {
//********************
// If action is LOG IN
if (isset($_POST['action']) and $_POST['action'] == 'login') {
if (!isset($_POST['username']) or $_POST['username'] == '' or !isset($_POST['passwd']) or $_POST['passwd'] == '') {
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$user_id = authenticate_username_password($db_con, $_POST['username'], $_POST['passwd']);
if ($user_id !== false && $user_id > 0) {
$_SESSION['reloadcounter'] = 1;
$_SESSION['username'] = $_POST['username'];
$_SESSION['user_id'] = $user_id;
$_SESSION['user_def_page'] = 1; //get_user_default_page($db_con, $user_id);
$user_roles = get_user_roles($db_con, $user_id);
$_SESSION['max_role_id'] = $user_roles['max_role_id'];
$_SESSION['sel_role_id'] = $user_roles['last_role_id'];
$goto = isset($_POST['goto']) ? $_POST['goto'] : HTTPS_SERVER;
header('Location: ' . $goto);
exit;
} else {
$GLOBALS['loginError'] = 'Wrong username or password!';
return FALSE;
}
}
//*********************
// If action is LOG OUT
if (isset($_POST['action']) and $_POST['action'] == 'logout') {
$user_ses_id = session_id();
try {
$stmt = $db_con->prepare("DELETE FROM gui_sessions WHERE session_id=?");
$stmt->execute(array($user_ses_id));
} catch (PDOException $e) {
log_error('PDO_CONN', $e->getCode(), $e->getMessage(), TRUE, $db_con);
}
session_regenerate_id(true);
unset($_SESSION['reloadcounter']);
unset($_SESSION['username']);
unset($_SESSION['user_id']);
unset($_SESSION['user_def_page']);
unset($_SESSION['max_role_id']);
unset($_SESSION['sel_role_id']);
$goto = isset($_POST['goto']) ? $_POST['goto'] : HTTPS_SERVER;
header('Location: ' . $goto);
exit;
}
//************************************
// If no action see if user logged in
$user_ses_id = session_id();
$datenow = convert_time_to_utc_date(time());
try {
$stmt = $db_con->prepare("UPDATE gui_sessions SET lastused_UTC=? WHERE session_id=?");
$stmt->execute(array($datenow, $user_ses_id));
if ($stmt->rowCount() == 1) {
return TRUE;
} else {
unset($_SESSION['reloadcounter']);
unset($_SESSION['username']);
unset($_SESSION['user_id']);
unset($_SESSION['user_def_page']);
unset($_SESSION['max_role_id']);
unset($_SESSION['sel_role_id']);
return FALSE;
}
} catch (PDOException $e) {
log_error('PDO_CONN', $e->getCode(), $e->getMessage(), TRUE, $db_con);
if (DEBUG_ON) {
echo 'SESSION UPDATE FAILED<br>';
}
return FALSE;
}
}
//******************************************************************************
//SESSION CONTROL
if (!authenticate($db_con)) {
include 'login.html.php';
exit();
}
include 'page.html.php';
?>
login.html.php:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p class="login-error"><?php if(isset($loginError)) { echo $loginError; } else { echo ' '; } ?></p>
<form id="login" action="" method="POST" name="login">
<label for="username">Username:</label><br />
<input name="username" type="text" size="40" value="" tabindex="0" /><br />
<label for="passwd">Password:</label><br />
<input name="passwd" type="password" size="40" value="" tabindex="1" /><br />
<input type="hidden" name="goto" value="https://localhost/test-login/"/>
<input type="hidden" name="action" value="login"/>
<input type="submit" class="button login" value="Login" tabindex="2"/><br />
</form>
<div><?php echo '<pre>' . var_dump($_SESSION) . '</pre>'; ?></div>
</body>
</html>
page.html.php:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<h1>Hello world!</h1>
<?php echo '<pre>' . var_dump($_SESSION) . '</pre>'; ?>
</div>
</body>
</html>
EDIT: I have track the error more and it seems that while Xdebuging the $_POST variables are okay, but standalone PHP interpreter is losing them some how.
Strange is also that I create the session to database inside if(isset($_POST['action']) && $_POST['action'] == 'login') and the php does not seem to get in there but it is able to Insert the session in database inside that if clause.
EDIT: Braking this till very peaces helped me to found one big mistake which still should not affect to the ACTUAL problem but made it much more harder to found.
Cause I have forgot to add curly brackets to if-else in the end of authenticate, the function always unset the session variables. In the beginning I thought that the function is not able to set them but it's actually unsetting them after redirection to "$_SERVER['PHP_SELF']". Anyway this should not happen if the UPDATE gui_session statement would work. But it made it much harder to see where is the problem. Here is the correction for index.php:
//************************************
// If no action see if user logged in
$user_ses_id = session_id();
$datenow = convert_time_to_utc_date(time());
try {
$stmt = $db_con->prepare("UPDATE gui_sessions SET lastused_UTC=? WHERE session_id=?");
$stmt->execute(array($datenow, $user_ses_id));
if ($stmt->rowCount() == 1) {
return TRUE;
} else {
unset($_SESSION['reloadcounter']);
unset($_SESSION['username']);
unset($_SESSION['user_id']);
unset($_SESSION['user_def_page']);
unset($_SESSION['max_role_id']);
unset($_SESSION['sel_role_id']);
return FALSE;
}
} catch (PDOException $e) {
log_error('PDO_CONN', $e->getCode(), $e->getMessage(), TRUE, $db_con);
if (DEBUG_ON) {
echo 'SESSION UPDATE FAILED<br>';
}
return FALSE;
}
The problem is that this update fails. But i have no idea why.
$stmt = $db_con->prepare("UPDATE gui_sessions SET lastused_UTC=? WHERE session_id=?");
$stmt->execute(array($datenow, $user_ses_id));
if ($stmt->rowCount() == 1) {
return TRUE;
}
If I try in php myadmin:
UPDATE gui_sessions
SET lastused_UTC='2013-08-04 12:00:00'
WHERE session_id='03dfgpiu1jl8idcjf191hqv4m2'
It affects 0 row, but if i do:
SELECT *
FROM gui_sessions
WHERE session_id='03dfgpiu1jl8idcjf191hqv4m2'
It returns 1 row
Okay. Problem solved. I'll leave the answer here if someone somehow runs to similar problem. I still don't know what the Xdebug did to hide this problem.
The problem was that I was trying to authenticate user by updating the last_used field in database session table. I assumed that if query is able to update that field the session must be valid. So I check if sql update last_user rows affected equals to 1, then users php-session-id is in session table. Problem is that MySQL returns 0 rows affected if the field has already the value that is updated "reference". And in my case that's of course true, cause the session last_update field is just created in log in procedure.
BUT it was very painful to find the problem cause Xdebug was doing something very strange there and after 0 rows affected update query it jumped out of the function without going to the else statement of the if-clause where I check if the number of affected rows equals to 1.
Comment if you have idea why Xdebug was behaving this way.