Session variables are lost after some time or instantly in php - php

Whenever the user login on my page the username is stored as a $_SESSION variable like so:
$_SESSION['username'] = $username;
where $username is the email address of the user and further user is assumed to be logged in. What I have observed is that my user is automatically logged out instantly after logging in or after few times. Are my session variables lost or what other problem should be?
My session_start() is always at the beginning and there is no space above it, so this is not the problem.
The part of my login code when login is successful is:
if ($usererror != 1 && $passworderror != 1 && $conferror != 1) {
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header('Location:/dashboard_test/index.php');
}
The first page that accepts login has the first few lines as:
session_start();
$username = $_SESSION['username'];

Related

How to prevent user from going back to login page after successfully logging in?

Here's my sample code for preventing user from entering the page using direct URL
<?php
ob_start();
include("../include/userlogin.php");
include('../include/database.php');
if(!isset($_SESSION))
{
session_start();
}
if($_SESSION['usertype'] != "admin"){
$_SESSION['message'] = "You cannot access only admin is allowed!";
header("location: login.php?success=1");
}
ob_end_flush()
?>
How to achieve this after the user successfully logged in, how can I prevent that user from going back to login page by clicking the back button in google chrome?
You can have another session variable to be TRUE when login is successful and false if not successful. Then you can check if the variable is true on the login page and redirect the user to the required page.
The $_SESSION container can store when a user was logged in and will be unset when not.
<?php
session_start();
if(isset($_POST["login"])){
$user = "";
$passwd = "";
if(isset($_POST["user"]))
$user = $_POST["user"];
if(isset($_POST["passwd"]))
$passwd = $_POST["passwd"];
if(stripslashes($user) == "user" &&
stripslashes($passwd) == "passwd")
{
$_SESSION["user"] = "user";
}
}
if(isset($_GET["logout"]))
session_destroy();
if(isset($_SESSION["user"]) && $_SESSION["user"] != "user")
include "internalPage.php";
else
include "loginPage.php";

Sessions and session variables are not working

I have a login script in Php. If the credentials are correct then the session is started, session variables are set and then redirected to the profile page. In the profile page, I have a script that redirects the user back to login page if they have not logged in.
Now, whenever I enter the correct credentials of the user and click on login, it redirects me back to the login page. To solve it, I commented out the code which was responsible for the redirection back to the login page. As a result, I got access to the profile page but I could not access the session variables.
And sometimes this code runs perfectly while sometimes it shows the above-stated problem.
The login code is as shown in the picture :
session_start();
require_once 'includes/config.php';
if(isset($_POST['login'])){
$user = trim($_POST['username']);
$pass = trim($_POST['password']);
$ch = $_POST['position'];
$stmt = $db->prepare("SELECT C_Name, PAN_id, Password FROM master_registration WHERE PAN_id = ?");
$stmt->bindParam(1,$user);
$stmt->execute();
$row = $stmt->fetch();
$username = $row["PAN_id"];
$Name = $row["C_Name"];
$hash = $row["Password"];
if(password_verify($pass, $hash)) {
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
$_SESSION["Name"] = $Name;
header("Location: main_folder/master/profile.php");
Login page code
The profile page code is as shown in the picture:
session_start();
require_once '../../includes/config.php';
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] !== true){
header("location:../../index.php");
exit;
}
$user = $_SESSION['username'];
profile page code
The seems fine, but there is a problem in sessions, plus it works in localhost but when I hosted in CPanel the problem starts.
Please help anyone...
Sometimes the Cpanel need config on the PHP SESSION, php.ini
First yo can check the CPanel session.save_path and enabel output_buffering .
to used phpinfo()
Your code its correct. but if try session_start(); to inculed the config.php file
Change your profile pic code with this code...
Your logic is incorrect thatswhy you are redirected everytime
if(!$_SESSION['loggedin']) {
header("location: ../../index.php");
exit() ;
}

Using variables with PHP session

I'm trying to get a user on my web shop to enter a username which will then be displayed on each page. I've started the session here in header.php and set the username variable:
session_start();
$_SESSION['username'] = $username;
$username = ''; //set blank variable to be filled in index
I'm then calling header.php in index.php using:
<?php
include "header.php";
?>
Inside of the logIn div I'm then asking for the username to be entered (no form to submit it yet, haven't gotten that far without running into the problem below). The script should show a message if the user isn't logged in alongside a form to log in, but if they have submitted a username to use then the form should display a welcome message:
<div class="logIn">
<?php
if (!isset($_SESSION['username'])) {
echo 'Welcome, '.$_SESSION['username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
</div>
I'm currently getting this error:
Notice: Undefined variable: username in /header.php on line 13
but I can't figure out why. I thought I'd declared it as empty, but even when I give it a value the if statement in index.php isn't working as intended.
How can I set up a simple session and accept a username variable (no password) which will then be displayed on index.php?
Your error is simple .
$_SESSION['username'] = $username;
$username = '';
You are trying to use $username before assigning it.
$username = '';
$_SESSION['username'] = $username;
Should be better !
I guess line 13 is this one $_SESSION['username'] = $username; ?
If you are assigning $username to $_SESSION['username'] it must be set somewhere before, I can't see that in your example.
Your code has to look something like this:
//declare $username
$username = "somename";
$_SESSION['username'] = $username;
Or if you set $username in a condition or something else you can try this:
$_SESSION['username'] = ( isset( $username ) ) ? $username : '';

Session not being saved after logging in

Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.

PHP login script requires user login twice

The login system I have created logs the user in fine initially, the user is redirected to an index as expected. However when the user clicks on a navigation link to navigate to another page (which is restricted) the user is redirected to the login page. When they login for a second time, every and any page can be accessed properly.
I tried printing out the session id and did a dump of the session array. I noticed when the user goes to the login in page a first they have session id "x", then they are redirected to the index page where they still have the session id "x". However when they try to navigate to another page on the site they are redirected to the login page and have the session id "y". When they login for a second time every pages shows them having session id "y".
What can be causing the session id to be changed after the user is redirected?
Here is my login script.
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$submit = $_POST['submit'];
$error = '';
if(isset($submit)){
// Check if fields are filled out
if($username == '' or $password == ''){
$error = 'Please enter a Username and Password';
}else{ // Proceed with login process
// See if user exists
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($query)<1){
echo 'Invalid Username/Password Combination';
}else{ // Grab user's information
$user = mysql_fetch_assoc($query);
if($password == $user['password']){//Login Success, Redirect and set Session Vars
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $user['username'];
$_SESSION['name'] = $user['first'];
$_SESSION['auth'] = $user['authorization'];
session_write_close();
header("Location: home.php");
exit;
}else{
$error = 'Invalid Username/Password Combination';
}
}
}
}
and the page restriction script:
session_start();
if(isset($_SESSION["loggedIn"])){
echo '<div align="right" id="user">Welcome '.trim($_SESSION['name']).'! Sign Out | Edit Account</div>';
}else{
header("Location: login.php");
}
Try setting the session variables on the restricted page.
session_start();
$_SESSION["loggedIn"]
$_SESSION["loggedIn"];
$_SESSION['username'];
$_SESSION['name'];
$_SESSION['auth'];
for debugging purpose please set print_r($_SESSION) on each page and see if it is printing correctly... you can set a value and see if it is carrying cross pages...
I was having very similar problem and discovered that having GET parameters in the link to the page that was not recognizing set session values was the problem. Although session_start() was the first line on the page script causing a need to log in a second time, the GET parameters in the link on the previous page were being processed as the first lines on the requested page (at least that is my guess as to why).

Categories