The weirdest thing is happening, when I logout of my app it redirects me to the correct page, so the script runs. However when I randomly type in a page that I should not have access to since my sessions and cookies have been destroyed I have access to it, this only happens on my hosted server, on local host it works fine, has anyone run into this before?
The start sessions script
<?php
session_start();
// If the session vars aren't set, try to set them with a cookie
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['user_email'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_email'] = $_COOKIE['user_email'];
$_SESSION['lawyer_client'] = $_COOKIE['lawyer_client'];
}
}
?>
The log out script
<?php
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id'])) {
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 7600);
}
// Destroy the session
session_unset();
session_destroy();
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 7600);
setcookie('user_email', '', time() - 7600);
setcookie('lawyer_client', '', time() - 7600);
// Redirect to the home page
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);}
?>
I am checking to see if the session is set using this script
require_once('startsession.php');
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
So after looking at what I just put down my first guess would be that my logout script is not properly clearing my sessions...but why is it only not doing it on my shared host?
In some shared hosts you will have to include the sessions directory in order to work. Are you sure that the sessions are correctly initialized?
Related
how to create cookie or session that not expires on browser close i created some cookies and session they work till i close browser or logingout but i dont want like this i want the sessions and cookies remain if and only if
the users logout by theirself from website
and this is login.php session and cookie after email and password verification become true:
$_SESSION['loggedIn'] = true;
$cookie_name = "user";
$cookie_value = "websitename";
setcookie($cookie_name, $cookie_value);
header("location:profile.php");
and this is what profile.php session:
if ( !$_SESSION['loggedIn'] ) {
header("location: index.php");
}
and this is what logout.php session and cookie:
session_unset();
session_destroy();
setcookie("user", "", time() - 3600);
also this is the index.php cookie and sesssion:
if(isset($_COOKIE['user'] ) || isset($_SESSION['loggedIn']) )
{
header("location:profile.php");
}
I built a PHP/MySql login system for a website I am working on and all was working fine. I took a month off from working on it, pulled it up last night, and all of a sudden it doesn't work. It recognizes if a wrong username or password was entered, but if you enter the correct information it redirects you to the login page again. Was there some update somewhere that I am unaware of? I did not change anything in any of my files. It was working perfectly a month ago, and with no change at all it doesn't work now. Any ideas?
UPDATE
It is working if I check the remember me box, but not if I don't I will paste my code below:
Login Script:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
session_name('TheLoginSession');
session_start();
// ---------- LOGIN ----------
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['remembercheck'] = (int)$_POST['remembercheck'];
$storedsaltquery = mysql_fetch_assoc(mysql_query("SELECT rand FROM members WHERE usr = '".$_POST['username']."'"));
$storedsalt = $storedsaltquery['rand'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,compid,usr,firstName,level,yn FROM members WHERE usr='{$_POST['usernamelog']}' AND pass='".hash("sha256",$_POST['passwordlog'].$storedsalt)."'"));
if($row['id'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['comp']=$row['compid'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['firstName'];
$_SESSION['usrlevel'] = $row['level'];
$_SESSION['new'] = $row['yn'];
$_SESSION['remembercheck'] = $_POST['remembercheck'];
// Store some data in the session
setcookie('Remember','remembercheck',time()+1209600,'/','.domain.com');
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo header("Location: ../index.php");
exit;
}
Index Page:
<?php
define('INCLUDE_CHECK',true);
require 'includes/connect.php';
require 'includes/functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('TheLoginSession');
// Starting the session
session_start();
if($_SESSION['id'] && !isset($_COOKIE['Remember']) && !$_SESSION['remembercheck'])
{
// If you are logged in, but you don't have the Remember cookie (browser restart)
// and you have not checked the remembercheck checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_SESSION['id'] && $_SESSION['new'] != 1){
header("Location: home.php");
exit;
}
?>
How can there be an update if nothing's changed?
Are you using a CMS or framework?
If it's all your own code, and you haven't changed anything, then nothing would have updated.
I've had an issue like this before but without more information, hard to know if it is the same issue. Mine had the symptom you describe (login with bad creds and get the authentication error, login with good creds and redirect back to login).
Mine was due to failing to include code to remove old session cookies. The login attempt 'works' but an old cookie also read and attempts to authenticate, fails (because it is too old), and kicks the user back to login.
If this is your issue, clear your site cookies and see if you can then log in.
If that works, you'll want to add some cleanup code to your logout and stale session handling. For instance, for logging out:
// per http://www.php.net/manual/en/function.session-destroy.php
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
session_destroy();
Again, just guessing at your issue here.
I have made a login and register system, which works flawlessly, and I am very proud of, but I cannot seem to get a logout function working.
My login system basically takes the database and scans it for rows that have both the username and password specified, and if it does, then it makes $_SESSION['loggedin']=1; and if it fails it makes it equal to 0.
Once the user is done, he/she clicks on a link that redirects to logout.php, and that is where the issues start. I have put session_start(); at the beginning of each page, but session_destroy, session_unset, and combinations of the two cannot seem to kill the session.
So I am wondering, is there a way that upon loading logout.php, it sets the $_SESSION['loggedin] to 0, and then redirects back to index.php(my homepage)? Which means it doesnt kill the session, but it would effectively log the user out. Any help is appreciated.
// Four steps to closing a session // (i.e. logging out)
// 1. Find the session
session_start();
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
if session_destroy doesn't work, use instead:
unset($_SESSION['put your session in here']);
// logout.php
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1) {
$_SESSION['loggedin'] = 0;
header('Location: index.php');
}
It redirects the user to to index.php, if $_SESSION['loggedin'] equals to 1, and sets $_SESSION['loggedin'] to 0.
I suggest you to have 3 files
1) login.php
session_start();
/*if user $_POST username and password is correct then*/
$_SESSION['loggedin'] = 1;
?>
2)logout.php
<?php
session_start();
unset($_SESSION['loggedin']);
$_SESSION['loggedin'] = 0;
?>
3)checkLogin.php
<?php
session_start();
if ( isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 0 )
{
echo "<script type='text/javascript'>alert('You need to login !')</script>";
echo '<meta http-equiv="Refresh" content="0;URL=index.php" />';
flush();
exit();
}
?>
with 3 files if you want to control some page that require login before access you just include(checkLogin.php);
e.g. index.php is not require login then not include(checkLogin.php);
but memberProfile.php is require login before then include(checkLogin.php);
I'm testing the implementation of a security check in my PHP sessions. I can successfuly detect whether the session was started from another IP address and I can successfully start a new session. However, the data from the old session gets copied into the new one! How can I start a blank session while preserving the previous session data for its legitimate owner?
This is my code so far, after lots of failed attempts:
<?php
// Security check
if( isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address'] ){
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
$tmp = session_id();
session_write_close();
unset($_SESSION);
session_id($tmp);
session_start();
}
// First time here
if( !isset($_SESSION['ip_address']) ){
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['start_date'] = new DateTime;
}
The official documentation about sessions is terribly confusing :(
Update: I'm posting some findings I got through trial and error. They seem to work:
<?php
// Load the session that we will eventually discard
session_start();
// We can only generate a new ID from an open session
session_regenerate_id();
// We store the ID because it gets lost when closing the session
$tmp = session_id();
// Close session (doesn't destroy data: $_SESSION and file remains)
session_destroy();
// Set new ID for the next session
session_id($tmp);
unset($tmp);
// Start session (uses new ID, removes values from $_SESSION and loads the new ones if applicable)
session_start();
Just call session_unset after session_regenerate_id to reset $_SESSION for the current session:
if (isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address']) {
// Check failed: we'll start a brand new session
session_regenerate_id(FALSE);
session_unset();
}
when a new user connects to your server, the script should only be able to access that user's session variables. you will want to store other info in a hashed session variable to verify that the session is not being jacked. if it is being jacked, no reason to start a new session, maybe just exit the script with a warning.
here is the function a lot of people use for fingerprinting a session:
function fingerprint() {
$fingerprint = $server_secure_word;
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$ip_blocks; $i++) {
$fingerprint .= $blocks[$i] . '.';
}
return md5($fingerprint);
}
Use this
unset($_SESSION['ip_address'])
instead of 'unset($_session)'
You can also use session_destroy.
session_destroy will destroy session data. For example,
session_start();
$_SESSION["test"] = "test";
session_write_close();
session_start();
// now session is write to the session file
// call session_destroy() will destroy all session data in the file.
session_destroy();
// However the you can still access to $_SESSION here
print_r($_SESSION);
// But once you start the session again
session_start();
// all session data is gone as the session file is now empty
print_r($_SESSION);
will output
array([test] => "test")array()
Greetings,
I am working on a login system and getting stuck with Blackberry browsers authenticating. It seems they have an issue with PHP's session_regenerate_id(), can someone suggest an alternative? Here are the auth and login scripts:
UPDATE
It would appear that sessions in general are not working. Took out session_regenerate_id() just to see if it would work and it just redirects me every time, as though the $_SESSION['MD_SESS_ID']were blank. Really stuck here, any ideas would be appreciated. Cookies on the device are enabled, using a Blackberry Bold 9650. It works on my iPod Touch and every browser on my PC.
Login
<?php
session_start();
include $_SERVER['DOCUMENT_ROOT'] . '/includes/pdo_conn.inc.php';
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return $str;
}
$username = clean($_POST['username']);
$password = clean($_POST['password']);
if ($username != "" && $password != "") {
$getUser = $db->prepare("SELECT id, username, password, salt FROM uc_dev WHERE username = ? LIMIT 1");
$getUser->execute(array($username));
$userDetails = $getUser->fetch();
$dbPW = $userDetails['password'];
$dbSalt = $userDetails['salt'];
$hashedPassword = hash('sha512', $dbSalt . $password);
if ($hashedPassword == $dbPW) {
//Login Successful
session_regenerate_id();
$_SESSION['MD_SESS_ID'] = $userDetails['id'];
header('Location: http://somewhere.com');
session_write_close();
} else {
header('Location: http://www.somewhere.com');
exit();
}
} else {
header('Location: http://somewhere.com');
exit();
}
?>
Auth
<?php
//Start the session
session_start();
//Verify that MEMBER ID session is present
if(!isset($_SESSION['MD_SESS_ID']) || (trim($_SESSION['MD_SESS_ID']) == '')) {
$_SESSION = array();
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
header("Location: http://somewhere.com");
exit();
}
?>
A while ago, I was doing some Blackberry development, and found out that the browser couldn't handle multiple cookies with the same name. Not sure if they've fixed this yet.
So if you're sending out the Set-Cookie header more than once (using setcookie, session_start, or session_regenerate_id), using the same name each time, this could be causing your problem.
You might want to keep track of the cookies you need to output, in an object or array, and only send them to the browser at the very end of the request. This way, if you need to change their values in the middle of the request, you can just overwrite the array's value, rather than sending out another cookie header.
This page may also help -- someone linked to it from PHP's session_regenerate_id page.