I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks
<?php
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
session_start();
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.
Is has to be like this:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
It's because you're always looking in $_POST for your user data.
Bring the session_start() out of that condition:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
You said that you called session_start() at the top of your login page, but you did not mention your other pages. session_start() needs to be called at the top of every page in your application. I generally put my session_start() logic, along with a snippet of code for logging the user out after a period of inactivity, in an include file and then include it at the top of every page.
<? session_start();
if (isset($_SESSION["last_activity"]) && (isset($_SESSION["username"])) && ((time() - $_SESSION["last_activity"]) > 900))
{
unset($_SESSION["username"]);
}
else
{
$_SESSION["last_activity"] = time();
}
?>
Related
Is it possible to use a session in PHP to track how long a user has not been active (no movement/scrolling/clicking) for. Without having to include the php script in the top of every single page throughout the website. For example in my login script I set some session variables after a successful login:
login script:
if ($pwdCheck == true) {
// Starting a session now to be able to create the variables!
session_start();
// Then creating session variables.
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['last_login_timestamp'] = time(); // testing this one here
}
Then in the top of each page throughout the website I have this:
<?php
require 'header.php'; // This includes my db login details
if((time() - $_SESSION['last_login_timestamp']) > 10){
echo $_SESSION['last_login_timestamp']; //nothing echo's at the mo
header('Location: scripts/logout-script.php');
}
?>
Logout script:
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
?>
Is this safe enough to use and is there a more efficient way of checking how long a user has been inactive for, than pasting the if((time() statement script in the top of each file?
I have a php site that some times when I load a page gets $_SESSION values from another user, but when I refresh the page it's all ok.
For example, I logged in as User A, navigate through the site and then in a page I get the session from User B. I refresh the page and get again the correct info from User A.
This is the file "db.php" that use with require_once in every file in my site. I put this at the very beginning of all my scripts:
<?php
if(!isset($_SESSION)){session_start();}
$mysqli = new mysqli("localhost", "", "", "");
if ($mysqli->connect_errno) {
echo "Error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset("utf8");
include("functions.php");
date_default_timezone_set('America/Mexico_City');
?>
Also I use a shared hosting, which has this values set:
session.gc_maxlifetime = 604800;
session.save_path = /var/cpanel/php/sessions/ea-php56;
I have a "header.php" required once in each page, that has this query to get and show the username of the current user. This is where I get noticed that something is wrong with the session, but I don't know why:
$query=sprintf("SELECT * FROM tblusers WHERE user=%s",$_SESSION['ADMINID']);
$info=$mysqli->query($query);
$c=$info->fetch_assoc();
The login is done in this way. cpass() is a function that crypts the pass to check it against the database. The login is done ok, and after some browsing I encounter the problem:
<?php
if(isset($_POST['user'])&&isset($_POST['pass'])){
$user=$mysqli->real_escape_string(trim($_POST['user']));
$pass=cpass($mysqli->real_escape_string(trim($_POST['pass'])));
$query=sprintf("SELECT * FROM tblusers WHERE user=%s AND pass='%s'",$user,$pass);
$check=$mysqli->query($query);
if($check->num_rows==1){
$r=$check->fetch_assoc();
$_SESSION['ADMINID']=$r['userid'];
session_regenerate_id(true);
header("Location: /");exit;
}
}
?>
The logout is handled this way:
<?php
if(!isset($_SESSION)){session_start();}
$_SESSION=array();
unset($_SESSION);
session_unset();
session_destroy();
if(isset($_GET['url'])){
header("Location: ".$_GET['url']);
}else{
header("Location: /");
}
?>
Thanks in advance!
Simple fix, when you have a login script that works, you can provide something like this at the end of it to give them a $SESSION tied in with their userID in your database.
Login.php
//login code
.....
//
//if successful
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /home.php" );
die();
And then at the top of your homepage ( I presume this is where you want an echo like you are logged in as 'user123'
home.php
<?php
session_start();
if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
echo 'whatever you want here'
?>
I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!
session data not displaying on logging in for the 1st time but its displaying once logging out and logging in again.
Anything can i do to display session data on example.com/page2.php on logging in for the first time ?
example.com/page1.php
<?php
session_start();
$_SESSION['id'] = 1;
$_SESSION['name'] = 'dummy name';
$_SESSION['email'] = 'dummy#dummymail.com';
header("Location: http://example.com/page2.php");
?>
example.com/page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
session_start();
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>
example.com/logout.php
<?php
session_destroy();
header("Location: http://example.com/page1.php");
?>
You should call
session_write_close();
before
header("Location: ...");
to ensure that the session data set in page 1 is written to disk before page 2 is requested.
In addition, it seems that using
header("Location: ...");
on page 1 will leave the $_SERVER["HTTP_REFERER"] value unset on page2.php. I tested this by changing page2.php to
<?php
echo "<pre>";
echo htmlspecialchars(print_r($_SERVER, true));
echo "</pre>";
if ($_SERVER["HTTP_REFERER"] == "http://example.com/page1.php")
{
session_start();
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
}
?>
Logout
If you try the same you may see that
[HTTP_REFERER] => http://example.com/page1.php
is not listed in the $_SERVER array on page 2.
On page 1, just to test, instead of using
header("Location: ...");
try using
echo 'Page 2';
and you should find that when you request page1.php then click on the Page 2 link, $_SERVER["HTTP_REFERER"] value will be set on page 2.
So is seems that your problem may include redirection not setting $_SERVER["HTTP_REFERER"]. Once you change your scripts to resolve this issue you may have a better change or sorting out the session issue.
You might like to try
page1.php
<?php
session_start();
$_SESSION["id"] = 1;
$_SESSION["name"] = "Dummy";
$_SESSION["email"] = "dummy#example.com";
session_write_close();
header("Location: page2.php");
?>
page2.php
<?php
session_start();
if (isset($_SESSION["id"]) && ($_SESSION["id"] == 1))
{
echo $_SESSION["id"];
echo $_SESSION["name"];
echo $_SESSION["email"];
echo 'Logout';
}
else
{
echo 'You are not logged in. Login';
}
?>
logout.php
<?php
session_start();
$_SESSION = array();
session_write_close();
echo 'You have been logged out. Login Test login status';
?>
I know this is necroing a 4 year old thread, and you were not having the exact situation but here's what I found:
I was having a problem with my welcome message saying 'Welcome, [user]!'. I couldn't get it to display until I logged out and logged in again, similar to your question title.
<?php
//says "Welcome, (whatever the user's name is)!"
$welcomemessage = "Welcome, " . $_SESSION["user"] . "!";
if ($_SESSION["loggedIn"] === 'y') {
echo $welcomemessage; }
?>
On my change username page, I changed the session variable to my new username, like so:
$_SESSION["user"] = $newusername;
which is changing it from the initial username, since your old username would be set as the current session variable even if you've changed it.
So, if I change my username from John to Jeff, anything which would mention John will be changed to Jeff immediately as the 'new username' variable is displayed, rather than having to log out then log in for the code to take your new username from the database and display it.
I know this won't help you as it's been 4 years, but this was the closest question I could find to my problem and wanted to share my simple solution for anyone else who looks this up :)
You forgot session_start() on your logout.php.
<?php
session_start(); //<------- Here
session_destroy();
header("Location: http://example.com/page1.php");
?>
and comment this on page2.php
<?php
if ($_SERVER['HTTP_REFERER'] == 'http://example.com/page1.php' )
{
ob_start();
//session_start(); <----- Comment this as shown
echo $_SESSION['id'];
echo $_SESSION['name'];
echo $_SESSION['email'];
}
?>
<a href = 'example.com/logout.php'>Logout</a>
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);