Regarding to How do I expire a PHP session after 30 minutes?, I copied some code from the 2nd answer Simple way of PHP session expiry in 30 minutes. I'd like to combine login and information to 1 page and another page is logout.php
here is my code.
homepage.php
if(isset($_POST["submitform"])){
$v1 = "admin";
$v2 = "admin";
$v3 = $_POST['username'];
$v4 = $_POST['password'];
if($v1 == $v3 && $v2 == $v4){
session_start();
$_SESSION['username'] = $v1;
$_SESSION['start'] = time(); // taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (1* 30) ; // ending a session in 30 seconds
if(!isset($_SESSION['username'])){
echo "Please Login again <a href='logout.php'>Click Here to Login</a>";
}else{
$now = time(); // checking the time now when home page starts
if($now > $_SESSION['expire']){
session_destroy();
echo "Your session has expire ! <a href='logout.php'>Click Here to Login</a>";
}else{
echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
}
}
}else{
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
echo '<font color="red">wrong password</font>"';
}
}else{
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
}
?>
Logout.php
<?php
session_start();
session_destroy();
header('Location: homepage.php');
?>
I set session expire to 30 seconds, however I found the session doesn't expire as expected. The session never expire. I am wondering if i put session_start(); in a right place? Thanks
You are only checking the status of the session on form post.
If you refresh the page it will resend the post, logging you in and extending the session.
Your logic needs to be:
if post, check password and extend session.
check if session has expired (this must happen if post there or not, makes no difference.)
based on the outcome of the session check display either a login form or the log out message.
if (isset($_POST["submitform"])) {
$v1 = "admin";
$v2 = "admin";
$v3 = $_POST['username'];
$v4 = $_POST['password'];
if ($v1 == $v3 && $v2 == $v4) {
session_start();
$_SESSION['username'] = $v1;
$_SESSION['start'] = time();
// taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (1 * 30);
// ending a session in 30 seconds
} else {
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
echo '<font color="red">wrong password</font>"';
die();
}
if (!isset($_SESSION['username'])) {
echo "Please Login";
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
} else {
$now = time();
// checking the time now when home page starts
if ($now > $_SESSION['expire']) {
session_destroy();
echo "Your session has expired ! <a href='logout.php'>Click Here to Login</a>";
} else {
echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
}
}
session_start() needs to be the first line of code.
In addition, you could set the cookie to expire.
is that possible to have different sessions on the same page?
YES
So use
One user, one session. Period.
http://us3.php.net/manual/en/ref.session.php
Related
We have a session logout script like:
<?php
//24 2 2015
session_start();
session_destroy();
header("location:login.php")
?>
now this script logouts and redirect it to login page where, username and password will be required to login again.
what if i wanted to have a temporary logout where after logging out it will direct us to a login page where it will only require password, cause session hasn't been destroyed and username is been passed to that page...
so, when you enter the password, it will check the input in database table where username = session username.
Hope i was clear.
The update::
templogout.php
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:templogin.php")
?>
templogin.php
<?php
//24 2 2015
session_start();
?>
<form id="msform" action="templogincheck.php" method="post">
<fieldset>
<input type="password" name="password" placeholder="Enter password here" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
templogincheck.php
<?php
//15 2 2015
session_start();
$Cser =mysqli_connect("localhost","text","text","text") or die("Server connection failed : ".mysqli_error($Cser));
$password = md5($_REQUEST["password"]);
$mobile = $_SESSION['mobile'];
$s = "select * from users where password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index.php");
}
else
{
header("location:/templogin.php");
}
?>
index.php
<?php
//15 2 2015
session_start();
unset($_SESSION["temp_logout"]);
if(!isset($_SESSION["login"]))
header("location:login.php");
?>
I hope i did it right, but i have to presume i have something wrong cause it isn't working..
Am i passing the session mobile to the login check page?
user first login page:
<form id="msform" action="ulogincheck.php" method="post">
<fieldset>
<h2 class="fs-title">LogIn</h2>
<h3 class="fs-subtitle">Please Enter your details accordingly<br/><br/> <small>(case sensitive)</small></h3>
<input type="text" name="email" placeholder="Email" required />
<input type="text" name="mobile" placeholder="Mobile" required />
<input type="password" name="password" placeholder="Password" required />
<button type="submit" name="submit" class="submit action-button"> LogIn </button>
</form>
first logincheck page
session_start();
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$password = md5($_REQUEST["password"]);
$s = "select * from users where email='".$email."' and password = '".$password."' and mobile = '".$mobile."'";
$result = mysqli_query($Cser,$s);
$count = mysqli_num_rows($result);
if($count>0)
{
$_SESSION["email"] = $email;
$_SESSION["mobile"] = $mobile;
$_SESSION["login"]="1";
header("location:/index2.php");
}
else
{
header("location:/usersignin.php");
You could add a "temp_logout" field to the $_SESSION variable and when you redirect the user to the login page, you can check for it $_SESSION["temp_logout"] and if it is true, add the username in the input field.
logout script:
<?php
//24 2 2015
session_start();
$_SESSION['temp_logout'] = true;
header("location:login.php")
?>
login page:
session_start()
...
//where the "username" input is
<input name="username" <?php if(isset($_SESSION["temp_logout"]){
echo 'value="'.$_SESSION["username"] .'" ';
} ?> />
...
after a successfull login:
<?php
session_start();
unset($_SESSION["temp_logout"]);
?>
Also, anywhere on the site, don't forget to check if the user is temporarily logged out; then immediatelly redirect him to the login page
it is really depend on your platform:
You can only unset something like password instead of destroying session,
unset($_SESSION['password']);
or set another key in session:
$_SESSION['loggedIn'] = false;
and redirect to login page.
also you can put username in cookie and destroy session.
setcookie
If you want to store username in cookie it is better to encrypt it for security reasons.
NOTE: Before we get started, YES I understand this is not the most secure type of login. I am comfortable using this. However if you can modify this to work with MySql I will use that instead, but I cannot seem to get this script to work anymore after I added the cookies to it. What did I do wrong? Thanks in advance.
<?php
if(isset($_COOKIE['user']) && isset($_COOKIE['pass'])) {
$user = $_COOKIE['user'];
$pass = $_COOKIE['pass'];
}
else {
$user = $_POST['user'];
$pass = $_POST['pass'];
}
if($user == "user" && $pass == "pass") {
setcookie("user", $user, time() + (86400 * 30), "/"); // 86400 = 1 day
setcookie("pass", $pass, time() + (86400 * 30), "/"); // 86400 = 1 day
echo 'Logged In';
}
else {
if(isset($_POST))
{?>
<form method="POST" action="test.php">
<label for="user">User</label> <input type="text" name="user"></input><br/>
<label for="pass">Pass</label> <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php}
}
?>
The content I am securing with this, is just basic PHP forms. Nothing that can be used to harm my site if someone did get into this. Just don't want everyone accidentally accessing it.
I strongly advise against you using this in any kind of production environment, but if it's what you want to use then that's fine too.
I'll be showing you how to implement sessions instead of cookies here.
The very first step: Whenever you use sessions, the very first thing you need to do on every script that uses those sessions is to start the session with:
session_start();
Now for session the session, that's simple. All you need to do is add an index to the $_SESSION superglobal:
$_SESSION['user'] = $user;
The trick though is not to force your user to login through the procedure you currently have. A session means the user is authenticated, so you don't want to force them to login again. What you want to do is add a check at the top of your file like this:
<?php
session_start(); // start the session
if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
die(header("Location: admin.php")); // user is logged in, send them to admin/user only page...
}
Which ends up leaving your "Login" script looking like this:
<?php
session_start(); // start the session
if(isset($_SESSION['user']) && !empty($_SESSION['user'])) {
die(header("Location: admin.php")); // user is logged in, send them to admin/user only page...
}
if(isset($_POST['submit'])) {
if($user == "user" && $pass == "pass") {
$_SESSION['user'] = $user;
die(header("Location: admin.php"));
} else {
// add some sort of error handling here because the user had invalid credentials.
}
} else {
?>
<form method="POST" action="">
<label for="user">User</label> <input type="text" name="user"></input><br/>
<label for="pass">Pass</label> <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}
?>
Here you go. Not sure why this mattered but it worked for me. (I changed the cookie duration too, but that wasn't part of the fix.)
<?php
if(isset($_COOKIE['user']) && isset($_COOKIE['pass'])) {
$user = $_COOKIE['user'];
$pass = $_COOKIE['pass'];
}
else {
$user = $_POST['user'];
$pass = $_POST['pass'];
}
if($user == "user" && $pass == "pass") {
setcookie("user", $user, time() + (1800), "/"); // 86400 = 1 day
setcookie("pass", $pass, time() + (1800), "/"); // 86400 = 1 day
echo 'Logged In';
}
else {
if(isset($_POST))
{?>
<form method="POST" action="test.php">
<label for="user">User</label> <input type="text" name="user"></input><br/>
<label for="pass">Pass</label> <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}}
?>
I changed your:
<?php}
}
?>
to:
<?php
}}
?>
I am beginner in using php cookies and I am trying to make a simple login and logout form using cookies. everything was good but when I press logout link I can't logout. and to logout I have to delete the cookies from the browser.
log_in page
<?php
session_start();
if (isset($_COOKIE["Email"])){
header("location: home.php");
}
?>
<form method="post" action="log_in.php">
<font size="6">Sign In</font>
Email Address: </b></font><input type="text" name="Email" id="email" />
password: <input type="password" name="password" id="password" />
<input type="checkbox" name="rememberMe" value="1" id="check"/> Remember Me
<input type="submit" name="Login" id="sign" value="sign in" >
<?php
include 'db.php';
if(isset($_POST['Login'])){
$user_email = $_POST['Email'];
$password = $_POST['password'];
$check_user = "SELECT * FROM user where user_email = '$user_email' AND user_pass = '$password'";
$run = mysql_query($check_user );
if (mysql_num_rows($run) > 0){
$_SESSION['Email']= $user_email;
$_SESSION['start'] = time();
if(isset($_POST['rememberMe'])){
$expire=time()+120;
setcookie("Email", "Email", $expire);
}
else{
$expire=time()+30;
setcookie("Email", "Email", $expire);
}
echo "<script>window.open('home.php','_self')</script>";
}
else {
echo "<script>alert('email or password incorrect!')</script>";
}}
?>
home page
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo 'logout';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) {
session_destroy();
header("location: log_in.php");
}}
logout page
<?php
session_start();
unset($_SESSION['Email']);
session_destroy();
header("Location: log_in.php");
if(isset($_SESSION['Email'])):
setcookie($_SESSION['Email'],'',time()-7000000,'/');
endif;
?>
Your home page (code) doesn't have session_start(); least not in what you posted; it's required when using session_destroy(); it doesn't work on its own.
Give this a go:
Sidenote: $expire is undefined for home page code, so you will need to use the same or similar method as you used for the other pages.
<?php
if (isset($_COOKIE["Email"])){
echo "Welcome " . $_COOKIE["Email"] . "!<br>";
echo 'logout';
}
else{
$now = time(); // Checking the time now when home page starts.
if ($now > $expire) { // $expire is undefined
session_start(); // <= required
session_destroy(); // <= does not work on its own
header("location: log_in.php");
}
}
If you're looking to completely destroy the session, you can just use session_destroy()
<?php
session_start();
session_destroy();
?>
Or if you are just looking to unset the Email, you can use
<?php
session_start();
if(isset($_SESSION['Email']))
unset($_SESSION['Email']);
?>
i have written a php login script which uses both session and cookies.
i know that sessions expire after closing the browser,but cookies exist till their expiration time is reached. in my script i created a COOKIE to store "username" of the logged in user.
After logging in , if i close the browser and re-open it..i must still remain logged in because of the cookie.And when i click log out i must be logged out.
But my script is not working properly because,after clicking the "logout" button link my script is not logging me out.
Here's the php code that i wrote:
<?php
session_start();
require_once('login/connectvars.php');
if(!isset($_SESSION['username']) && isset($_COOKIE['username']))
{
$_SESSION['username'] = $_COOKIE['username'];
}
if(isset($_POST['submit']))
{
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$username = mysqli_real_escape_string($dbc,trim($_POST['username']));
$password = mysqli_real_escape_string($dbc,trim($_POST['password']));
$query = "SELECT user_id,username FROM users_dns WHERE username = '$username' AND password = SHA('$password')";
$data = mysqli_query($dbc,$query) or die(mysqli_error($dbc));
if(mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('username',$row['username'],time() + (60 * 60));
echo 'success';
mysqli_close($dbc);
}
else
{
echo 'enter correct username and password';
}
}
else
{
echo 'no empty fields please..';
}
}
?>
Here's what i used in the html code:
<?php
if(isset($_SESSION['username']))
{
echo 'logged in as'.$_SESSION['username'];
echo 'log out ('.$_SESSION['username'].')<br />';
echo $_SESSION['username'];
}
else
{
?>
<div id="login_form">
<!--<span class="error"><?php echo $error_msg; ?></span>-->
<form id="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr>
<th>Username:</th>
<th>Password:</th>
</tr>
<tr>
<td><input type="text" name="username" /></td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Log In" class="submit" /></td>
<td><input type="button" class="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
</div>
<?php
}
?>
Here is my log out script
<?php
session_start();
if(isset($_SESSION['username']))
{
$_SESSION = array();
if(isset($_COOKIE['session_name()']))
{
setcookie('username','',time() - 3600);
}
session_destroy();
}
setcookie('user_id','',time() - 3600);
setcookie('username','',time() - 3600);
echo 'redirecting you...please wait..';
header("Refresh: 3;url=http://localhost/");
?>
if(isset($_COOKIE['session_name()']))
this should be
if(isset($_COOKIE['username']))
because you have created username cookie and you are checking for session_name() cookie.
i've a problem with php session handling that i can't explain to myself.
I'm studying php from scratch, and i can't figure out how to mantain a session live:
This is my index page, where a user can login or register to the database visiting the right page, and then come back to see if he's logged in:
Code:
Index
<?php session_start(); ?>
Register
Login
<?php
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin'];
?>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
else
{
echo "Please Register or Login";
}
?>
In fact this work, because when i come back from login.php it says, "Logged as: Admin"
But when i click on the link to get the login page, or register page again from the index page, i should get the same message, "Logged as...", but the session appear to be closed instead. :(
here's login.php:
<?php
session_start();
include "dbConnect.php";
if(isset($_SESSION['login']))
{
echo "Logged as: ".$_SESSION['nlogin']; // IT NEVER SHOW THIS MESSAGE
}
if(isset($_POST['submit']) &&(trim($_POST['submit']) == "Login"))
{
if(!isset($_POST['user']) || $_POST['user']=="")
{
echo "Attenzione inserire l'username.";
}
elseif(!isset($_POST['pwd'])||$_POST['pwd']=="")
{
echo "Attenzione inserire la password.";
}
else
{
$u = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));
$u = str_replace(" ","_",$u);
$p = trim(filter_var($_POST['pwd'], FILTER_SANITIZE_STRING));
$p = sha1($p);
$istance = new dbHandle;
$istance->connect();
$data = $istance->query("SELECT * FROM login WHERE username_login = '$u' AND password_login = '$p'");
if(mysql_num_rows($data) == 0)
{
echo "Failed";
echo "<a href='index.php' target='_self'> Go Back </a>";
}
else
{
echo "Logged";
$res = $istance->getdata($data);
$_SESSION['login'] = $res->id_login;
$_SESSION['nlogin'] = $res->username_login;
echo "<a href='index.php' target='_self'> Go Back </a>";
}
}
}
else
{
?>
Login
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input name="user" type="text" size="20" required="required"/>
...
<input name="pwd" type="password" size="20" required="required"/>
...
<input type="submit" name="submit" value="Login"/>
</form>
<form method="post" action="<?php unset($_SESSION['login']) ?>">
<input type="button" name="logOut" value="LogOut" />
</form>
<?php
}
$istance->disconnect();
?>
When i come back using the link above "Go Back" to the index page, it shows Logged as...
but when i come back here again, it does not.
So i assume my session were destroyed automatically? but why?
Thanks, i appreciate your help.
I forget to say that PHP.ini has
session.cookie_lifetime
set to "0"
Thanks
You are calling unset($_SESSION['login']) many times. It removes your login:
<form method="post" action="<?php unset($_SESSION['login']) ?>">
Try this:
<form method="post" action="index.php">
<input type="button" name="logOut" value="LogOut" />
</form>
<? if (isset($_REQUEST['logOut'])){ session_destroy(); } ?>
unset the session like below
if(isset($_REQUEST['logOut']))
{
unset($_SESSION['login']);
}
You check for if(isset($_SESSION['login'])).
If that results in true, you do <form method="post" action="<?php unset($_SESSION['login']) ?>">
Note the unset($_SESSION['login']) part - after that, if(isset($_SESSION['login'])) will return false.
Session overview :
<?php
// Always Start our session
session_start();
$_SESSION['username'] = 'Saurabh Singh';
$username = $_SESSION['username'];
echo $username;
if(isset($_SESSION['username']))
{
Do your action
}
else
{
echo "Please Register or Login";
}
I don't think the session has been destroyed!
I would start by first removing all the empty lines between the opening tags for php and the
session_start().
Test it again and you could add the line
error_reporting(E_ALL);
below the session_start to see if any error messages are echo(ed) back to you.
In your PHP.ini what
session.cookie_lifetime = 0
means is that the session remain active so long as the browser stays open. It's only destroyed when the browser is closed.
I hope this helps