Session seemingly quitting when page is reloaded - php

I set session variables on a login page, and then it redirects to the home page, where a function called isLoggedIn() decides whether it include()s signed-in.php or membership-container.php in the header. signed-in.php is what shows if the person is logged in, and membership-container.php is shown if the client is not logged in. After I login it shows signed-in.php as would be expected, but when I reload the page, it shows membership-container.php.
Login page:
<!DOCTYPE html>
<?php
session_start();
/*error_reporting(0);*/
require 'users/database/connect-database.php';
require 'users/database/database-functions.php';
if ($_POST) {
$email = sanitize($connection, strip_tags($_POST['login_email']));
$password = sanitize($connection, strip_tags($_POST['login_password']));
$encrypted_password = sha1($password);
if (!empty($email) && !empty($password)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Your email is not valid.';
} else if(exists($connection, 'email', 'members', 'email', $email) == false) {
$error = "We didn't find anyone with that email and password. Have you joined SamHalesJr.com yet?";
} else if (exists($connection, 'email', 'members', 'password', $encrypted_password) == false) {
$error = "Please enter the correct password.";
} else if (detail($connection, 'active', 'members', 'email', $email) != 1) {
$error = "You haven't activated your account!";
} else {
$query = login($connection, $email, $encrypted_password);
if ($query == true) {
ini_set('session.gc_maxlifetime', $inactive_session);
$_SESSION['session'] = time();
$_SESSION['logged_in'] = detail($connection, 'user_id', 'members', 'email', $email);
if (isLoggedIn()) {header('Location: /home');}
}
}
} else {
$error = 'Please enter an email and password.';
}
}
require 'users/database/disconnect-database.php';
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form action="/login" method="POST">
<input placeholder="Email" value="<?php echo $email; ?>" type="text" name="login_email"><br>
<input placeholder="Password" value="<?php echo $password; ?>" type="password" name="login_password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
I know connect-database.php and disconnect-database.php work, and here are the contents of database-functions.php:
<?php
$inactive_session = 7200;
function sanitize($connection, $data) {
return mysqli_real_escape_string($connection, $data);
}
function exists($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$count = mysqli_num_rows($query);
return ($count >= 1) ? true : false;
}
function generate($password) {
$password = hash('sha512', $password);
return $password;
}
function isLoggedIn() {
if (isset($_SESSION['logged_in'])) {
return true;
} else {
return false;
}
}
function detail($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$associate = mysqli_fetch_assoc($query);
return $associate[$detail];
}
function login($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query);
if ($count >= 1) {
return true;
} else {
return false;
}
}
function logout() {
unset($_SESSION['logged_in']);
session_unset();
session_destroy();
}
?>
Am I correct that the session_start() and any other $_SESSION[''] variables need to go before the <html> tag? Here is the code that I put before the <html> tag in each page:
<?php
include 'users/database/database-functions.php';
ini_set('session.gc_maxlifetime', $inactive_session);
session_start();
if (isset($_SESSION['session']) && (time() - $_SESSION['session'] > $inactive_session)) {
logout();
}
$_SESSION['session'] = time(); // Update session
?>
Leave a comment if there is any other info that you need and thanks so much for anyone's help. I've been working on this for a long time and am still new to session handling and functions.
Just to make it clear, my problem is that when I enter the ___correct___info to /login and click the login button, it redirects to the /home page as it should do and it shows signed-in.php in the header, but when I reload /home it shows membership-container.php.
If it helps at all, after I have reloaded the home page (after logging in), it still shows the PHPSESSID cookie, just as it does when it shows signed-in.php. It also says that the cookie expires "when the browsing session ends." I don't know if that means anything, but that fact that it still shows the PHPSESSID cookie could mean that the session is still alive and that the error is in my isLoggedIn() function.
Also it might help to see what exactly is inside the header:
<?php if (isLoggedIn()) {
include 'signed-in.php';
} else {
include 'membership-container.php';
} ?>
Thank you anyone who helps me out with this.

Related

I can't get userid from session?

some help if you wish please for beginner user
will you please show me where is my code problem ?
i want to get user id from $_SESSION['userid']
but it's not working
i success to get username but not the id
i include session_start(); on each page to want to use it
but it's not showing the user id
only username working
here are my code
<?php
include("conn.php");
// variable declaration
$userid = "";
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['userid']);
unset($_SESSION['user_type']);
header("location: ../login.php");
}
// return user array from their id
function getUserById($id){
global $conn;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// LOGIN USER
function login(){
global $conn, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($conn, $query);
if (mysqli_num_rows($results) == 1) { // user found
// Storing username in session variable
session_start();
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
$userid=$row['id'];
$username=$row['username'];
$user_type=$row['user_type'];
$_SESSION['username'] = $username;
$_SESSION['userid'] = $userid; // <-this variable should now exist
$_SESSION['user_type'] = $user_type;
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
if ($logged_in_user['user_type'] == 'superuser') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: superuser/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
} }else {
array_push($errors, "Wrong username/password combination");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isSuperuser()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'superuser' ) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
// escape string
function e($val){
global $conn;
return mysqli_real_escape_string($conn, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>
As far as i can tell, your script would run.
Though please note that when using with sessions and $_SESSION globals, you have to initialise it first by adding session_start(); at the top of your page.
You should also dig into using PDO rather than mysqli or mysql.
I know this looks complicated, but it's the safest way to handle database queries.
Also don't use md5, use password_hash();
I also recommend adding var_dump($row); in this if statement, to see what data you are working with:
if (mysqli_num_rows($results) == 1) { // user found

Make function to check login status with session in PHP

i want to make toefl test. so there will be a login button. when someone login in, then the login button will be logout button. but when i login in, the login button was not changed. please help me
function to check login status (i save this function in lib_function.php):
<?php session_start(); ?>
<?php
function check_login(){
$hasil = 0;
if (isset($_SESSION['email'])) {
$mail = $_SESSION['email'];
}
if (isset($_SESSION['pass'])) {
$pass = $_SESSION['pass'];
}
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
?>
index.php:
<?php session_start();
require_once("connection.php");
?>
<?php include("lib_function.php"); ?>
<--header-->
<?php
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
this is my login process:
<?php
session_start();
require_once("connection.php");
$email = $_POST['email'];
$password = $_POST['password'];
$cekuser = mysql_query("SELECT * FROM user WHERE email = '$email'");
$jumlah = mysql_num_rows($cekuser);
$hasil = mysql_fetch_array($cekuser);
if($jumlah == 0) {
echo "<script>alert('Email has registered!'); window.location = 'index.php'</script>";
} else {
if($pass > $hasil['password']) {
echo "<script>alert('Wrong password!'); window.location = 'index.php'</script>";
} else {
$_SESSION['email'] = $hasil['email'];
header('location:index.php');
}
}
?>
You check if $_SESSION['pass'] is set in your check_login function, but you never set it during the login process.
Either set $_SESSION['pass'] or remove and !empty($pass) from check_login().
Always try to check if the Session is already active before starting one. You also might want to assign default values of say NULL to the $mail & $pass variables inside your check_login() function because at a point, you were checking if $mail and $pass were empty. What if they were not even set at all? In this case those variables would not have existed at all...
<?php
// FILE:: lib_function.php
function check_login(){
$hasil = 0;
// GET THE $mail & $pass FROM SESSION; ASSIGNING A DEFAULT NULL
// TO EACH OF THEM IF THEY ARE NOT YET SET...
$mail = isset($_SESSION['email']) ? $_SESSION['email'] : null;
$pass = isset($_SESSION['pass']) ? $_SESSION['pass'] : null;
if (!empty($mail) and !empty($pass)){
$hasil = 1;
}
return $hasil;
}
// FILE:: index.php
// START SESSION ONLY IF IT IS NOT ALREADY ACTIVE:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
require_once("connection.php");
include("lib_function.php");
// HEADER HERE
$check = check_login();
if ($check == 1){
echo "Login <strong class=\"hover\">";
}else{
echo "Logout <strong class=\"hover\">";
}
?>
try this:
function login($email) {
$_SESSION['email'] = $email;
}
function is_logged() {
return isset($_SESSION['email']);
}
function logout() {
session_destroy();
}

PHP login file is not working. Continues to return to the login page and not user profile

Here is the full code:
<?php
session_start();
session_regenerate_id(true);
require_once('connect.php');
require_once "lib.php";
require_once "utils.php";
$EmailAddress = mysqli_real_escape_string($link,htmlentities($_POST['EmailAddress']));
$Password = mysqli_real_escape_string($link,htmlentities($_POST['Password']));
$Fname = mysqli_real_escape_string($link,htmlentities($_POST['Fname']));
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(mysqli_num_rows($result) == 1)
{
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
{
$_SESSION['active']=true;
$_SESSION['EmailAddress']=$EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
}
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$_POST[EmailAddress]' AND
Password ='$_POST[Password]'";
$result = mysqli_query($link,$sql);
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
My guess is that the error is where the $sql = SELECT * FROM users WHERE but I', not entirely sure. I'll input the Email and the password, but it continues to return me to the login page. I'm not sure why it's doing that, but it needs to go to the Profile page once the user has logged in.
$link = "somethingrelatedtoyourdb";
$EmailAddress = $_POST['EmailAddress'];
$Password = $_POST['Password'];
//$Fname = $_POST['Fname']; THIS IS NEVER POSTED
echo "<pre>";
print_r($_POST);
echo "</pre>";
function login($result,$EmailAddress,$Password)
{
if($result)
{
if(($result) == true)//TRUE AGAIN
{
//THIS MAKES NO SENSE
// $email_exists = true;
// $pass_exists = true;
//if($pass_exists = true && $email_exists = true)
// {
$_SESSION['active'] == true;
$_SESSION['EmailAddress'] == $EmailAddress;
//$_SESSION['Password']=$Password;
header("Location: myIndex.php");
exit();
// }
}
else
echo "<div id='error'><h4>Error: Incorrect Password or Email</h4></div>";
}
}
function redirect_if_active()
{
header("Location: myIndex.php");
exit();
}
if(isset($_SESSION['active']) && $_SESSION['active'] ===true)
{
redirect_if_active();
}
// only processes login information if the submit button has been clicked
if (isset($_POST['submit'])) {
$sql="SELECT * FROM users WHERE EmailAddress ='$EmailAddress' AND
Password ='$Password'";
print_r($sql);
// $result = mysqli_query($link,$sql); Ill make this true for a moment
$result = true;
login($result,$EmailAddress,$Password);
}
if(isset($_POST['signup'])){
header("Location: register.php");
exit();
}
?>
<html>
<head></head>
<body>
<div id='form'>
<form action='example.php' method='POST'>
<div id='email'>Email:</div>
<div id='email2'>
<input name='EmailAddress' type='email'/>
<br>
</div> Password: <input name='Password' type='password'/>
<br>
<input class="submit" name='submit' type='submit' value='Login'/>
<input class="submit2" name='signup' type='submit' value='SignUp!'/> </form>
</body></html>
You have quite a few issues that I see right off the bat
In your sql query this $_POST[Password] should be $_POST['Password']. Same thing with the email address. This might fix your query, however please note, passing in raw post data to mysql is a big security problem. You are already setting these post params as escaped variables. You could use those, but you should look at prepared statements to keep yourself safe.
This block, has an error, and also doesn't make sense
$email_exists = true;
$pass_exists = true;
if($pass_exists = true && $email_exists = true)
It should be
if($pass_exists == true && $email_exists == true)
Or better yet
if($pass_exists && $email_exists)
However since you are explicitly setting both of these vars to true right before checking if they are true, then this will always be true.

when a user logs in send them to their own profile page

When a user logs in they are redirected to member.php, below is the log in code followed by member.php code.
login.php
<?php
session_start ();
include 'core/init.php';
$username = '';
$password = '';
$dbusername = '';
$dbpassword = '';
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
$numrow = mysql_num_rows ($query);
// user login
if ($numrow!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header("Location: member.php");
}
}
else
{
// admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
$numrow2 = mysql_num_rows ($query2);
if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header("Location: admin.php");
}
else{
echo "Incorrect password";
}
}
else{
if ($username!=$dbusername&&$password!=$dbpassword)
{die("That user does not exist!");
}
}
}
}
/*if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
if ($username!=$dbusername)
{die("That user does not exist!");
}
}
}
else
die("Please enter your email address and password");
*/
?>
member.php code (I know this is messy. Sorry, just need to get it working for now)
<div id="header">
<div id= "logout">
<?php
if(isset($_GET['username']) === true & empty ($_GET['username']) === false)
$username = $_GET ['username'];
if (user_exists($username) === true) {
echo "<p>Welcome, ".$_SESSION['Email']. "!<br><a href='logout.php'>Logout</a>\n<a href='index.php'>Back to homepage</a></p>";
?></div>
</div>
<div id="main-content">
<?php
//get username from user id
$MemberID = user_id_from_username($username);
$profile_data =user_data($MemberID, 'Name','Email');//Need to pull out stuff from oddjob table
?>
<h1><?php echo $profile_data['Name']; ?>'s profile</h1>
<p><?php echo $profile_data['Email'];?></p>
<?php
} else {
echo '<p>Sorry, cannot find that user on system.</p>';
}
?>
At the moment I have set member.php so that if I type a username (which is the users email address) into the URL it displays some profile data specific to that user.
However, when I log in as a user, and get redirected to member.php I just see a blank page and the username doesn't show up in the URL, just an error message saying ' Undefined variable: username' for that user and I don't know how to edit this so that it works and the member is sent to their own profile page.
Relevant functions below:
functions.php
function logged_in() {
return (isset($_SESSION['MemberID'])) ? true : false; //Email
}
function user_data($MemberID){
$data = array();
$MemberID =(int)$MemberID;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args >1) {
unset($func_get_args[0]);
$fields = '`' . implode('`,`', $func_get_args) . '`';
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `member` WHERE `MemberID` = $MemberID"));//expects parameter 1 to be resourse
return $data;
}
}
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `MemberID` FROM `member` WHERE `Email` = '$username'"),0, 'MemberID');
Init.php:
if (logged_in() ===true) {
$session_MemberID = $_SESSION['MemberID'];//undefined?
$user_data= user_data($session_MemberID,'MemberID','Name','Address','Postcode','DOB','Mobile','Email','Password','RepeatPassword');
exit();
}
To be honest Ive been looking at this code for so long now, I'm completely blind/lost as to how to fix this. Please help if you can.
Index.php
<div id= "login">
<form action="login.php" method="post">
<?php
if (logged_in() === true) {
echo "<p>Welcome, ".$_SESSION['Email']. "!<br><a href='logout.php'>Logout</a>";
}else
echo"<h4>Username: <input type='text' name='Email'><br>
Password: <input type='Password' name='Password'>
<input type='submit' value='Log In'><br>
<a href='register2.php'>Register?</a>
</form>"
?>
On your member.php page you try to get the username from $_GET but you don't pass any parameter when you redirect the user in login.php.
Either rely only on the $_SESSION which you set or change your redirect:
header('Location: member.php?username='.$username);
This header command:
header("Location: member.php");
Must be above the head. it can only be called if no other html code has been sent to the user. E.g.:
<?php
header("Location: member.php");
?>
<html>
<head>
</head>
<body>
</body>
</html>

PHP session problems

I have a login page and a 'member's area' page, the login code is here:
login.php
if ($account->is_logged_in())
{
$route->to(ACCOUNT_URL);
}
elseif (isset($_POST['username']))
{
if ($account->authenticates())
{
if ($account->log_in()) $route->to(ACCOUNT_URL);
}
else
{
$flash->set('error', 'The credentials you provided are incorrect.');
}
}
the functions (in a different file)
public function log_in ()
{
session_unset();
session_destroy();
if(session_start())
{
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $_POST['username'];
}
}
public function authenticates ()
{
$username = $_POST['username'];
$password = $_POST['password'];
if (ctype_alnum($username) && ctype_alnum($password))
{
$username = mysql_real_escape_string(filter_var($username, FILTER_SANITIZE_STRING));
$password = $this->encrypt(mysql_real_escape_string(filter_var($password, FILTER_SANITIZE_STRING)));
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Then my members area page:
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
login.php redirects me (meaning it authenticates my account), but when I get to members.php it echoes out 'not logged in' and that is all.
You'll need to call session_start() at the top of members.php (and any page that needs to access the $_SESSION.
// Must initiate the session to test if logged in.
session_start();
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
Do you have session_start() at the very beginning of all scripts which use sessions?

Categories