why the PHP session is destroyed when page is loading multiple time? - php

I have website where I am using login and logout functionality using php.
So, for login, first I call following function :
function sec_session_start() {
$session_name = 'happiechef_session_ids'; // Set a custom session name
$secure = false;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location:index");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
and then I call following function to check user login information from mysql database :
function admin_login($email, $pass) {
global $conn;
$query = mysqli_query($conn, "SELECT a_email, a_pass, a_id FROM admin_profile WHERE a_email = '$email' LIMIT 1");
$query_result = mysqli_fetch_array($query);
$a_id = (int) $query_result['a_id'];
$db_hash = htmlspecialchars($query_result['a_pass']);
$num = mysqli_num_rows($query);
if($num == 1) {
if (checkbrute($email) == true) {
// if true account is locked
return false;
} else {
if(verify($pass, $db_hash)) {
$a_id = preg_replace("/[^0-9]+/", "", $a_id);
$email = validate_data($email);
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['logged_admin_user'] = $email;
$_SESSION['logged_admin_id'] = $a_id;
$_SESSION['login_string'] = hash('sha512', $db_hash . $user_browser);
return true;
} else {
$time = time();
$query = mysqli_query($conn, "INSERT INTO login_attempt VALUES('', '$email', '$time')");
return false;
}
}
} else {
return false;
}
}
Well, when I refresh the page multiple time using F5 key from Keyboard it's automatically logged out and sometime when I visit other page it's asking me to login! Somehow it's destroyed the PHP session.
Can anyone tell me what is the problem in my code ?
Thanks In advance.
Update :
Here is the function to check if user is logged or not :
function admin_login_check() {
// Check if all session variables are set
if (isset($_SESSION['logged_admin_user'], $_SESSION['logged_admin_id'], $_SESSION['login_string'])) {
global $conn;
$user_id = $_SESSION['logged_admin_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['logged_admin_user'];
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if($query = mysqli_query($conn, "SELECT a_pass FROM admin_profile WHERE a_email = '$username' ")) {
$num = mysqli_num_rows($query);
if($num == 1) {
$result = mysqli_fetch_array($query);
$password = htmlspecialchars($result['a_pass']);
// if hash equals function is not exist
if(!function_exists('hash_equals')){
function hash_equals($str1, $str2){
if(strlen($str1) != strlen($str2)){
return false;
} else {
$res = $str1 ^ $str2;
$ret = 0;
for($i = strlen($res) - 1; $i >= 0; $i--) {
$ret |= ord($res[$i]);
}
return !$ret;
}
}
}
$login_check = hash('sha512', $password.$user_browser);
if (hash_equals($login_check, $login_string) ){
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}

If you remove the session_regenerate_id(true) the session should not destroyed anymore.
Why is this happening?
session_regenerate_id() replace the current session ID with a new one. The session information will be kept. When you use this function to often (reload, AJAX, etc.) you can see this effect on your session. PHP has a restriction for access to the session for only one running task. If you run session_regenerate_id() to often / fast the task get into queue. So the following is happening:
The first call changes the session ID and delete the old session (if parameter is true).
The second call has still the old session ID and tries to do some operations on it.
As the old session doesn't exists anymore, a new session would be created. The user is logged out now (session is invalid now).

Related

Login System in PHP for multi user

I am making a login system in php xampp. After correct authentication of the user they get redirected depending on what role they play. For Admin it goes to Admin Page and for Sales Person it goes to the main menu. In the code below you can see how the login is setup. Now my problem is: For example more than one user login as Sales they will be redirected to the main menu page. Now lets say user x logs in first then user y logs in. Now both are at the main menu page. Now when I refresh the page of the main menu I see user y's name even though I am as user x and on the same main menu page.
function Encrypt($Word)
{ //Encryption method
$ciphering = "AES-128-CTR"; //method of encryption
$options = 0;
// Non-NULL Initialization Vector for Encryption
$Encryption_iv = '1234567891011121';
// Store the Encryption key
$Encryption_key = "GeeksforGeeks";
// Use openssl_Encrypt() function to Encrypt the data
return openssl_encrypt($Word, $ciphering, $Encryption_key, $options, $Encryption_iv);
}
//Getting user information. SQL injection protection and XSS Attack.
$username = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['user'])));
$password = htmlspecialchars(mysqli_real_escape_string($con, $_POST['pass']));
/* $UserOption = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['Level'])));
$PinCode = htmlspecialchars(mysqli_real_escape_string($con, $_POST['Pin'])); */
$Option = htmlspecialchars(mysqli_real_escape_string($con, $_POST['option']));
$Hash = Encrypt($username);
$SalesHash = Encrypt($username);
$GetActivestmt = $con->prepare("SELECT Active FROM logins WHERE Username=?");
$GetActivestmt->bind_param("s", $Hash);
$GetActivestmt->execute();
$ActiveResult = $GetActivestmt->get_result();
//Fetching
if ($ActiveResult->num_rows === 0) exit("No Records");
while ($Active = $ActiveResult->fetch_assoc()) {
$ActiveRow = $Active['Active'];
}
$GetActivestmt->close();
global $ActiveRow;
$con->next_result();
/* if($UserOption == $row['User_Type'] && $Hash==$row['Username'] && password_verify($password, $row['HashPassword'])
&& $PinCode ==$row['PinCode']){
echo $row['User_Type'];
}else if($UserOption == $row['User_Type'] && $Hash==$row['Username']
&& password_verify($password, $row['HashPassword']) && $PinCode == $row['PinCode']){
echo $row['User_Type'];
}else{
echo '<script>alert("Info Mis-Match");</script>';
exit();
} */
if ($ActiveRow === 0) {
$GetLoginstmt = $con->prepare("SELECT * FROM logins WHERE Username=? LIMIT 1;");
$GetLoginstmt->bind_param("s", $Hash/* , $PinCode */);
$GetLoginstmt->execute();
$LoginResult = $GetLoginstmt->get_result();
//Fetching
if ($LoginResult->num_rows === 0) exit('<script>alert("User not found");</script>');
while ($Login = $LoginResult->fetch_assoc()) {
$Username = $Login['Username'];
$HashPassword = $Login['HashPassword'];
$UserType = $Login['User_Type'];
$Pin = $Login['PinCode'];
$ID = $Login['ID'];
}
$GetLoginstmt->close();
global $Username, $HashPassword, $UserType, $Pin;
echo "<script>alert('$Username');</script>";
$con->next_result();
if (
$Hash == $Username && password_verify($password, $HashPassword)
&& $Option == $UserType
) {
echo "<br/>";
if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url = "../PinCodes/VerifyPinForm.php"; //url to be redirected
echo '<script language="javascript">window.location.href ="' . $url . '"</script>'; //redirects the user to the main page
} else {
echo "Error in Query";
}
} else if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$_SESSION['SalesHash'] = $Username;
$_SESSION['User_ID'] = $ID;
// setcookie("Username", $Hash, time()+84600, "/", '', '', true);
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else {
echo "Error";
}
} else {
echo '<script>alert("Incorrect User Info");</script>';
}
} else {
echo '<script>alert("User Already Logged in.");</script>';
global $username, $password, $Option;
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date("Y/m/d");
$_SESSION['SalesHash'] = $SalesHash;
if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$url1 = "../PinCodes/VerifyPinForm.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
}
}
$con->close();
?>
<?php
require '../connection1.php';
function Decrypt($Word)
{ //decrypting data using openssl decrypt method
$ciphering = "AES-128-CTR";
$options = 0;
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
// Store the decryption key
$decryption_key = "GeeksforGeeks";
// Use openssl_decrypt() function to decrypt the data
return openssl_decrypt($Word, $ciphering, $decryption_key, $options, $decryption_iv);
}
if ($con) {
session_regenerate_id(true);
$User = $_SESSION['SalesHash'];
$UserID = $_SESSION['User_ID'];
$GetInfo = $con->prepare("SELECT * FROM logins WHERE Username=? AND ID=?");
$GetInfo->bind_param("si", $_SESSION['SalesHash'], $_SESSION['User_ID']);
$GetInfo->execute();
$GetResult = $GetInfo->get_result();
//Fetch info
if ($GetResult->num_rows === 0) exit(header("Location: ../Login/LogoutForm.html"));
while ($row = $GetResult->fetch_assoc()) {
$Active = $row['Active'];
$Username = $row['Username'];
$LoginTime = $row['Last_Login'];
$UserType = $row['User_Type'];
$ID = $row['ID'];
}
$GetInfo->close();
global $Active, $Username, $LoginTime;
}
if ($Active == 1 && $UserType == "Sales" && $Username == $User) {
} else {
header("Location: ../Login/Logout.html");
}
?>
This code is the main menu page. Now I don't know where I am going wrong.
I have started the session from xampp php.ini file.
You wouldn't need to store each salesperson in a session. What you want to do is store one user in the session, then have that user have access to many salespersons.
For instance your user table might have id, email address and password columns.
Then, your salespersons table would have id, user_id, and name.
In you session, you'd store which user_id was logged in. Then, one your page you could query something like SELECT * FROM salespersons WHERE user_id = $session['user_id']
If you use a modern PHP framework like Laravel you can handle this easily with relationships:
https://laravel.com/docs/7.x/eloquent-relationships
User authentication also comes baked out of the box:
https://laravel.com/docs/7.x/authentication
Edit: maybe I'm misunderstanding your question. If you dont want one user to access multiple salespeople, you don't need to worry about separating the sessions. A session by it's nature is a single user accessing your service. If you research how php sessions work there's a ton of resources out there to help get you started.

Auto check for user roles on login handler instead checking with sessions on every page?

I am trying to add a login to my site. I searched on the internet for examples I found two login systems
This one and this one
I want to use the second one this one looks more complete to me. I am not a coder and I need your advice.
I do check for user role with this code on every protected page
if(!$isLoggedIn || $_SESSION["role"] != admin) {
echo "you dont have permissions to access this page";
exit();
}elseif(!$isLoggedIn || $_SESSION["role"] != normal){
echo "you dont have permissions to access this page";
exit();
}elseif(!$isLoggedIn || $_SESSION["role"] != notactive){
echo "you must update your account";
exit();
}
First question. How can I integrate above codes with cookie check in sessionCheck.php
require_once "Auth.php";
require_once "Util.php";
$auth = new Auth();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
$isLoggedIn = false;
// Check if loggedin session and redirect if session exists
if(!empty($_SESSION["uid"])) {
$isLoggedIn = true;
}
// Check if loggedin session exists
else if(!empty($_COOKIE["member_login"]) && !empty($_COOKIE["random_password"]) && !empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username
$userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
// Validate random password cookie with database
if(password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if(password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if($userToken[0]["expiry_date"] >= $current_date) {
$isExpiryDareVerified = true;
}
// Redirect if all cookie based validation retuens true
// Else, mark the token as expired and clear cookies
if(!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDareVerified) {
$isLoggedIn = true;
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
}
}
The second question which one you recommend me to use?
This should work assuming $userToken contains the role attribute.
require_once "Auth.php";
require_once "Util.php";
$auth = new Auth();
$util = new Util();
// Get Current date, time
$current_time = time();
$current_date = date("Y-m-d H:i:s", $current_time);
// Set Cookie expiration for 1 month
$cookie_expiration_time = $current_time + (30 * 24 * 60 * 60); // for 1 month
$isLoggedIn = false;
$role = null;
// Check if loggedin session and redirect if session exists
if(!empty($_SESSION["uid"])) {
$isLoggedIn = true;
$role = (isset($_SESSION["role"]) ? $_SESSION["role"] : null);
}
// Check if loggedin session exists
else if(!empty($_COOKIE["member_login"]) && !empty($_COOKIE["random_password"]) && !empty($_COOKIE["random_selector"])) {
// Initiate auth token verification directive to false
$isPasswordVerified = false;
$isSelectorVerified = false;
$isExpiryDateVerified = false;
// Get token for username
$userToken = $auth->getTokenByUsername($_COOKIE["member_login"],0);
// Validate random password cookie with database
if(password_verify($_COOKIE["random_password"], $userToken[0]["password_hash"])) {
$isPasswordVerified = true;
}
// Validate random selector cookie with database
if(password_verify($_COOKIE["random_selector"], $userToken[0]["selector_hash"])) {
$isSelectorVerified = true;
}
// check cookie expiration by date
if($userToken[0]["expiry_date"] >= $current_date) {
$isExpiryDareVerified = true;
}
// Redirect if all cookie based validation retuens true
// Else, mark the token as expired and clear cookies
if(!empty($userToken[0]["id"]) && $isPasswordVerified && $isSelectorVerified && $isExpiryDareVerified) {
$isLoggedIn = true;
$role = (isset($userToken[0]["role"]) ? $userToken[0]["role"] : null);
} else {
if(!empty($userToken[0]["id"])) {
$auth->markAsExpired($userToken[0]["id"]);
}
// clear cookies
$util->clearAuthCookie();
}
}
if (!$isLoggedIn || $role != "admin") {
echo "you dont have permissions to access this page";
exit();
} else if (!$isLoggedIn || $role != "normal") {
echo "you dont have permissions to access this page";
exit();
} else if (!$isLoggedIn || $role != "notactive") {
echo "you must update your account";
exit();
}

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

setcookie() gives no error, but the cookie does not set

I have a application based on CodeIgniter . I tried to set cookie in on of my controller functions. Here is the part of my code
private function login_core($username, $user_pass){
//Get value from database
$this->load->model('user_model');
if($this->user_model->init($username) == 1){
$pass = $this->user_model->getPassword();
$this->e['db_pass'] = $pass;
//Now encrypt th real password
//Make thisL
$e_p = $username. $user_pass . $this->user_model->getEmail();
$e_p = sha1($e_p);
$this->e['act_pass'] = $e_p;
//Whenever the email is changed, update the password. (Require password to change the email)
$this->load->library('encrypt');
$this->load->library('xsecurity');
//cookie not set :( . And i don't know the reason
if($pass == $e_p){
$this->xsecurity->SetInfoLocal($e_p);
setcookie('y',$this->encrypt->encode($username, $_SERVER['HTTP_USER_AGENT']),60*60*24*3);
return true;
} else {
return false; //false'
}
} else {
return false;
}
}
public function login(){
if(!isset($_POST['user'], $_POST['pass'])){
$this->load->view('header');
$this->load->view('content/errorError');
$this->load->view('footer');
return false;
}
$user = $_POST['user'];
$pass = $_POST['pass'];
if(self::login_core($user, $pass)){
$d['a'] = $this->e;
$this->load->view('header', $d);
if(isset($_GET['redirect_to'])) {
ob_start();
header('location:'. $_GET['redirect_to']);
return true;
}
$data['userloggedOn'] = true;
$this->load->view('main', $data);
}
else
{
$data['userloggedOn'] = false;
$this->load->view('main', $this->e);
}
$this->load->view('footer');
}
The user points to login via a form, and to my thinking, no any headers are sent before setting cookie (for the login page).when i wrap if around setcookie, the result is true, but the cookie does not set? Why?
don't you need to added the current time to the expire date?
for example
setcookie("y", $unique_string, time() + (60*60*24*30), '/');

two php function in the same page conflict what can I change to?

I'm trying to protect page by making a member only area the code I use in this case is
<?php
include 'dbc.php';
page_protect();
?>
there is no error by using this code and also it just working fine
but the problem is that whenever I place the below code in the same page
the problem will happen with the iPhone, only with this device but the rest still ok, like PCs, laptop and tablet (iPad) they are all no problem
But the iPhone the problem will be that you can access to the page after login but whenever you refresh it will redirect you to the login page and ask for login again.
<?php
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "";
} elseif ($link == 23) {
echo "";
} else {
echo "";
}
?>
There is no error show or anything.
my question is that is there anyway to protect the page because I need this to be member only area and the above code is very important and need to be in the page.
Thanks in advance.
here is the dbc.php sorry about that but I copied the whole script and placed here
<?php
/*************** PHP LOGIN SCRIPT V 2.3*********************
(c) Balakrishnan 2010. All Rights Reserved
Usage: This script can be used FREE of charge for any commercial or personal projects. Enjoy!
Limitations:
- This script cannot be sold.
- This script should have copyright notice intact. Dont remove it please...
- This script may not be provided for download except from its original site.
For further usage, please contact me.
/******************** MAIN SETTINGS - PHP LOGIN SCRIPT V2.1 **********************
Please complete wherever marked xxxxxxxxx
/************* MYSQL DATABASE SETTINGS *****************
1. Specify Database name in $dbname
2. MySQL host (localhost or remotehost)
3. MySQL user name with ALL previleges assigned.
4. MySQL password
Note: If you use cpanel, the name will be like account_database
*************************************************************/
define ("DB_HOST", "xxxxxx"); // set database host
define ("DB_USER", "xxxxxx"); // set database user
define ("DB_PASS","xxxxxxx"); // set database password
define ("DB_NAME","xxxxxx"); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$user_registration = 1; // set 0 or 1
define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password
//define ("ADMIN_NAME", "admin"); // sp
/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);
/*************** reCAPTCHA KEYS****************/
$publickey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/**** PAGE PROTECT CODE ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/
function page_protect() {
session_start();
global $db;
/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}
// before we allow sessions, we need to check authentication key - ckey and ctime stored in database
/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) )
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */
$cookie_user_id = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {
logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/
if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_name'] = $_COOKIE['user_name'];
/* query user level from database instead of storing in cookies */
list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
} else {
logout();
}
} else {
header("Location: login.php");
exit();
}
}
}
function filter($data) {
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}
function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}
function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;
$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);
return $str . "...";
}
function isEmail($email){
return preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}
function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
return true;
} else {
return false;
}
}
function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}
function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }
if (strcmp($x,$y) != 0) {
return false;
}
return true;
}
function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function logout()
{
global $db;
session_start();
if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users`
set `ckey`= '', `ctime`= ''
where `id`='$_SESSION[user_id]' OR `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}
/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();
/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
header("Location: login.php");
}
// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($pwd . $salt);
}
function checkAdmin() {
if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}
}
?>
An alternative to your current protect script, ive made it without cookies:
<?php
//A basic login and session script I just whacked up
session_start();
/**
* cleanit cleans unwanted chars
*
* #param string $input
* #return clean string containing only a-zA-Z0-9.,_ -
*/
function cleanit($input){
return preg_replace('/[^a-zA-Z0-9\.,_ -]/s', '', $input);
}
/**
* auth function called on each page you want protected
*
* #param $_SESSION['user_name'] $logged_in_user
* #param $_SESSION['user_hash'] $hash
* #param $_POST['user'] (when logging in) $username
* #param $_POST['pass'] (when logging in) $password
* #param [login|check|logout] function control $exe
* #return $_SESSION gets set returns LOGGED_IN|ERROR:MULTI:USERS|ACCESS_DENIDE|ACCESS_TIMEOUT|ACCESS_LOGGED_OUT
*/
function auth($logged_in_user,$hash,$username,$password,$exe) {
global $db;
if ($exe=='login') {
//LOGIN////////////////////////////////////////////////
$result = mysql_query('SELECT * from users where username="'.cleanit(mysql_real_escape_string($username)).'" and password="'.cleanit(mysql_real_escape_string(sha1($password))).'"',$db);
$num = mysql_num_rows($result);
if($num=='1') {
session_regenerate_id();
$_SESSION['user_status']='LOGGED_IN';
while ($row = mysql_fetch_array($result)) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = $row['username'];
$_SESSION['user_hash'] = md5($_SERVER['REMOTE_ADDR']);
$_SESSION['user_ip'] = cleanit($_SERVER['REMOTE_ADDR']);
$_SESSION['user_date'] = time();
$_SESSION['user_level'] = cleanit($row['user_level']);
}
$result2 = mysql_query('REPLACE into users values ("'.mysql_real_escape_string($_SESSION['user_id']).'","'.mysql_real_escape_string($_SESSION['user_name']).'","'.mysql_real_escape_string(sha1($password)).'","'.mysql_real_escape_string($_SESSION['user_hash']).'","'.mysql_real_escape_string($_SESSION['user_ip']).'","'.mysql_real_escape_string($_SESSION['user_date']).'","'.mysql_real_escape_string($_SESSION['user_level']).'")',$db);
$return = 'LOGGED_IN';
return $return;
}elseif($num >='2') {
$result = mysql_query('DELETE from users where username="'.mysql_real_escape_string($username).'" and password="'.mysql_real_escape_string(sha1($password)).'"');
$error = 'ERROR:MULTI:USERS';
return $error;
}else {
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
$_SESSION['user_status']=='';
session_destroy();
$return = 'ACCESS_DENIDE';
return $return;
}
return $return;
}
if($exe=='check') {
//CHECK////////////////////////////////////////////
$result = mysql_query('SELECT hash,ip,user_date from users where username="'.mysql_real_escape_string($logged_in_user).'" and hash="'.mysql_real_escape_string($hash).'"',$db);
if(mysql_num_rows($result)==1) {
$rows = mysql_fetch_row($result);
$timeout = (time()-1800);
if($rows[2]<=$timeout){auth("","","","","logout");
return'ACCESS_TIMEOUT';
}
if($hash==$rows[0] && $_SERVER['REMOTE_ADDR']==$rows[1]) {
$return = 'LOGGED_IN';
mysql_query('UPDATE users set user_date="'.time().'"',$db);
return $return;
}else {
session_regenerate_id();
$return = 'ACCESS_DENIDE';
return $return;
}
}else{
session_regenerate_id();
$return = $_SESSION['user_status'];
return $return;
}
}
if($exe=='logout') {
//LOGOUT///////////////////////////////////////////
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
unset($_SESSION['user_status']);
session_destroy();
session_regenerate_id();
$return = 'ACCESS_LOGGED_OUT';
return $return;
}
if($exe=='') {
//BLANK////////////////////////////////////////////
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_hash']);
unset($_SESSION['user_ip']);
unset($_SESSION['user_date']);
unset($_SESSION['user_level']);
unset($_SESSION['user_status']);
session_destroy();
session_regenerate_id();
$return = 'FUNCTION.ERROR:DO.MISSING';
return $return;
}
return $return;
}
/*
SQL
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL DEFAULT '',
`password` varchar(45) NOT NULL DEFAULT '',
`hash` varchar(45) NOT NULL DEFAULT '',
`ip` varchar(45) NOT NULL DEFAULT '',
`user_date` varchar(45) NOT NULL DEFAULT '',
`user_level` varchar(45) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `username`, `password`, `hash`, `ip`, `user_date`, `user_level`) VALUES
(1, 'admin', '6c7ca345f63f835cb353ff15bd6c5e052ec08e7a', 'f528764d624db129b32c21fbca0cb8d6', '127.0.0.1', '1306757011', '1');
admin/admin1
*/
//Usage
/*--------------------------------*/
//login page
session_start();
if(isset($_REQUEST['user']) && isset($_REQUEST['pass'])){
$user=cleanit($_REQUEST['user']);
$pass=cleanit($_REQUEST['pass']);
$_SESSION['user_status'] = auth("","",$user,$pass,"login");
header('members.php');
}else{
//Show login form
}
/*--------------------------------*/
/*--------------------------------*/
//Members page
session_start();
//Checks login on each page request put this on all pages you want to protect
$_SESSION['session_status'] = #auth($_SESSION['user_name'],$_SESSION['user_hash'],"","","check");
if($_SESSION['session_status']=='LOGGED_IN'){
//Logged in norm user
}elseif($_SESSION['session_status']=='LOGGED_IN' && $_SESSION['user_level']==1){
//Logged in as admin
}else{
//Logged out
}
/*--------------------------------*/
//Logout
if($_REQUEST['do']=='logout'){
auth("","","","","logout");
header('Location: index.php');
}
?>
This is a comment posted here for better formatting.
You have to read the man pages on session_ functions work! Doing so will save you time and aggravation. Many here have given you hints on the possible source of your problem. For one, you cannot have ANY output whatsoever before session_start(). For 2, make sure you have error reporting turned on in your environnement.
if(!isset($_GET['link'])){
$link = 1;
} else {
$link = $_GET['link'];
}
if ($link == 1) {
echo "";
} elseif ($link == 23) {
echo "";
} else {
echo "";
}
This snippet at the top of your post will always make your script fail if you try to echo anything whatsoever. Again, friendly advice, take 15 minutes of your time and read the manual. You will have access to much more valuable first-hand information on those aspects of your work than by posting here out of laziness to get a quick fix. Then again, I probably am not the first one to tell you this.

Categories