Session variable being destroyed after migrating to live website - php

I've just migrated my website from my local WAMP server to a live HTTPS server on 1and1. It works perfectly on the local server, but on the live server the session variables are being destroyed when I'm trying to log in. I know the database is working fine and all the queries are running successfully after some testing.
The problem is that the session variable is being created when I run the log in script, but once the page reloads and runs a 'session check', the variable no longer exists. Because of this the site just reloads the login form as the if condition is not being met.
Here is the code for both scripts. I don't know why this is happening as the entire website is being run through HTTPS so its not an issue with HTTP/HTTPS etc.
LOGIN SCRIPT
<?php
date_default_timezone_set("Europe/London");
require("db_connect.php");
if ($sql)
{
$email = $_POST['userEmail'];
$password = $_POST['userPassword'];
$checkDetails = mysqli_query($sql, "SELECT * FROM users WHERE email='$email'");
while ($details = mysqli_fetch_array($checkDetails))
{
$hashedPassword = $details['password'];
if(password_verify($password, $hashedPassword))
{
//Passwords Match
//Update last login time in the database
$now = date("Y-m-d H:i:s");
$lastLoginQuery = mysqli_query($sql, "UPDATE users SET lastLogin='$now' WHERE email='$email'");
if ($lastLoginQuery)
{
//Initialise session
session_start();
$_SESSION['user'] = $email;
header("Location: ../");
}
else
{
echo "There was an error logging you in. Please try again!";
}
}
else
{
echo "The details you entered are incorrect. Please return to the login page. If the problem persists, contact an administrator.";
}
}
}
else
{
echo "There was a problem connecting to the database";
}
?>
SESSION CHECKING SCRIPT
<?php
//Check if a session exists and load the page if it does
session_start();
if (isset($_SESSION['user']))
{
//Check if the session has timed out
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
//Last user action performed more than 30 minutes ago. Log out now.
session_unset();
session_destroy();
header("Location:./");
}
//If the session hasnt timed out. Reset the last activity time.
$_SESSION['LAST_ACTIVITY'] = time();
//Continue to load content
include('./includes/main.php');
}
else
{
// Load login page
include('./includes/login_form.php');
}
?>

Session start must be the very first call in your script. https://www.w3schools.com/php/php_sessions.asp
<?php
session_start();
date_default_timezone_set("Europe/London");
require("db_connect.php");
etc...

Fixed the issue by adding an additional session_start(); directly at the beginning of the index.php file before any html. Seems strange that the login and session_check scripts wouldn't work without this as they also had session_start(); in them too.

Related

Allow content with $_Session

I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!

Php login system suddenly stopped working

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.

Login form always takes more then one try

I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?

PHP Upgrade 5.2 to 5.3 Session Issue

I'm going through the pain of upgrading PHP on my server from 5.2 to 5.3. Having migrated my old php.ini to the new and upgraded my mysql passwords, my PHP sessions no longer work.
This is my login code below, it executes correctly and even logs my login correctly in the activity log. (updatelog function) I have also posted my session valid check code.
Is there anything obvious in my login code that is no longer valid in PHP 5.3, having previously worked under 5.2?
// Login User///
if(#$_POST["dologin"] == 1)
{
//record login attempt
updatelog("",$_SERVER['REMOTE_ADDR'],"Login Attempt By: ".$_POST['username']);
$user_name = escape($_POST["username"]);
$password = escape(md5(SALT.$_POST["password"]));
$login = $query->GetSingleQuery("--SINGLE","SELECT user_name, id, user_email FROM url_users WHERE user_name='".$user_name."' and user_password='".$password."';",array("user_name","id","user_email"));
if(!isset($login['user_name'])) //failed login
{
$_SESSION['loggedin'] = 0;
//record failure
updatelog("",$_SERVER['REMOTE_ADDR'],"Login Failure By: ".$_POST['username']);
header("Location: index.php?failed=1&user=$user_name");
}else
{
//login valid
//get country details
$getcountry = $query->GetSingleQuery("--SINGLE","SELECT geo_ip.ctry FROM admin_adfly.geo_ip geo_ip WHERE INET_ATON ('".$_SERVER['REMOTE_ADDR']."') BETWEEN geo_ip.ipfrom AND geo_ip.ipto;",array("ctry"));
//set session items
$_SESSION['country'] = $getcountry['ctry'];
$_SESSION['username'] = $login['user_name'];
$_SESSION['userid'] = $login['id'];
$_SESSION['loggedin'] = 1;
$_SESSION['email'] = $login['user_email'];
//session salt
$hsh = md5($_SERVER['HTTP_USER_AGENT'].SALT);
$_SESSION['_XXX(*##!_D#R*&$%(){*#)_D_296']['user_agent'] = $hsh;
//update the ui transaction log
updatelog($login['id'],$_SERVER['REMOTE_ADDR'],"Login Success For: ".$_POST['username']);
// run function to check if any adverts have completed
adcomplete($_SESSION['userid']);
//redirect
header("Location: index.php");
}
}
// Check users login session is valid, this is called on each page I want to restrict by login. ////
if(isset($_SESSION['_XXX(*##!_D#R*&$%(){*#)_D_296']['user_agent']) == $_SERVER['HTTP_USER_AGENT'].SALT)
{
return 1; //session success
}else
{
return 0; //session failure
}
The check for login is not checking the hash of user agent and salt, should be :
if (isset($_SESSION['_XXX(*##!_D#R*&$%(){*#)_D_296']['user_agent']) == md5($_SERVER['HTTP_USER_AGENT'].SALT))
{
return 1; //session success
} else {
return 0; //session failure
}
Edit:
Since the problem persists and it seems to be a php configuration issue I would try to make the simplest php page that uses sessions and try it out in the 5.3 environment to confirm that it is a php configuration problem and use that simple page to test the configuration while trying to fix the issue.
A simple php page:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
if (isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views'] + 1;
else
$_SESSION['views'] = 0;
echo '<pre>';
var_dump(session_id()); // I should stay the same
var_dump($_SESSION); // I should start at 0 and increase
echo '</pre>';
Simple solution:
Go to /var/lib/php and set attributes 777 to "session" directory.
EDIT:
Yes, I know it is not recommended solution, but it works. For do it right, you should set owner to php, httpd or nginx - I don't have time to check which it should be
After much messing about, it turns out that the problem was related to the last session name, it was somehow invalidating the entire browser session, removing all data from the session.
After removing "(*##!_D#R*&$%(){*#)_D_296" from the $_SESSION array, my login session started working again.

Need help in login code of php?

This is my code for login. when i try to login at 1st time it pass blank value to session.but when i go back to login page again & signin that time it successfully signin.
i didnt understand whats wrong with this code?? plz help me.
session_unset();
session_start();
Global $i;
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/signinConfig.php");
function redirect($redirect=null)
{
header("Location : $redirect");
}
if (isset($_POST['submit']))
{
$check = mysql_query("SELECT * FROM user_reg WHERE `username` = '".$_POST['username']."'")or die("Dont Dare To Hack");
$check2 = mysql_numrows($check);
if ($check2 == 0)
{
die('That user does not exist in our database. Click Here To Register');
}
else
{
$i=0;
$password = mysql_result($check,$i,"password");
$_POST['pass'] = stripslashes($_POST['pass']);
$pass = md5($_POST['pass']);
if ($pass == $password)
{
$_SESSION['username']= mysql_result($check,$i,"username");
mysql_close();
redirect("/User_CP/user_cp.php");
}
else
{
die('Incorrect password, please try again.');
}
}
}//after this html code take place
in config file i store database connection code & session expire code. here it is
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1000)) { // last request was more than 30 minates ago
session_destroy(); // destroy session data in storage
session_unset(); // unset $_SESSION variable for the runtime
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Ok first of all, your redirect function is missing exit(); after header
function redirect($redirect=null)
{
header("Location : $redirect");
exit();
}
The problem is that if you dont give exit, the code will continue running after the redirect function.
for example, here you have
redirect("/User_CP/user_cp.php");
And it will redirect the page, but the php will still be running and if you have a session_destroy() or session_unset() function after that line it will be executed and the session will get expire.
It is also possible that even if the session is not being destroyed it might be causing some conflicts.
Try that exit() and let me know.

Categories