Logout when using cookies - 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']);
?>

Related

Deleting user cookie

I was able to set a user cookie up properly, but it won't get destroyed or terminated upon user logout. Any help would be greatly appreciated! I'm still new to php and learning.
Here's my code:
page1.php
<?php
session_start();
if(isset($_POST['txtusername']) && isset($_POST['txtpassword'])){
$_SESSION['username'] = $_POST['txtusername'];
$_SESSION['usertype'] = $_POST['usertype'];
$username = $_SESSION['username'];
setcookie("Activity99", $username, time()+3600);
echo "<font class = 'user'>".$username."</font>"."<br>";
}
?>
page2.php
<form method="POST" action="login.php">
<label><?php echo "<font class = 'user'>".$username."</font>";?>
<input type="submit" name="logout" value="Logout" class= "logout">
</label>
</form>
<?php
if(isset($_POST['logout'])){
if(isset($_COOKIE['Activity99'])):
setcookie('Activity99', $username, time()-3600,);
endif;
}
?>
Depending on how you actually read the login state, you'd have to end your session as well:
session_start();
$_SESSION = [];
setcookie("Activity99", "", time() - 3600);
header("Location: index.php?info=success");
die();
try this:
unset($_COOKIE['your cookie name']);
or:
setcookie('your cookie name','');

Variable $_SESSION does not want to be setted

So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)
You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();

PHPBB login script

after playing around with the script from all the help you people have given me I have come over another problem, when i click login on the login form it says: The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Now i do admit i am no script pro but this is the only script i can find on how to use a phpbb forum database on a external site. so my question is whats wrong with all the .php file i am about to show you and how can i repair them?
login.php
<?php
//ob
ob_start();
//session
session_start();
if (isset($_SESSION['username']))
{
header("Location: main.php");
exit();
}
//connect
$error = 'Zaoby Database ERROR! connection failture!';
mysql_connect('localhost','root','') or die ($error);
mysql_select_db('phpbbtest') or die($error);
//include functions.php php script
require 'forums/includes/functions.php';
if (isset($_POST['login']))
{
//get form data
$username = addslashes(strip_tags(strtolower($_POST['username'])));
$password = addslashes(strip_tags($_POST['password']));
if (!$username||!$password)
echo "please enter a username and password<p />";
else
{
//find username
$find = mysql_query("SELECT * FROM phpbb_users WHERE username_clean='$username'");
if (mysql_num_rows($find)==0)
echo "username not found<p />";
else
{
while ($find_row = mysql_fetch_assoc($find))
{
// grab password hash for user
$password_hash = $find_row['user_password'];
}
$check = phpbb_check_hash($password, $password_hash);
if ($check==FALSE)
echo "Incorrect password<p />";
else if ($check==TRUE)
{
$_SESSION['username']=$username;
header("Location: main.php");
exit();
}
}
}
}
?>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p />
<input type="submit" name="login" value="Log in">
</form>
main.php
<?php
//ob
ob_start();
//session
session_start();
$session_username = $_SESSION['username'];
if (!isset($_session_username))
{
header("Location: login.php");
exit();
}
else
{
echo "hello, ".$_session_username." <a href='logout.php'>Log out</a>";
}
ob_end_flush();
?>
logout.php
<?php
session_start();
session_destroy();
header("Location: login.php")
?>
P.S someone in my last question about this put something about using MySQLi instead of mysql_query and that i should put a ob_end_flush somewhere?
Try to use ob_start(); just after the
e.g. <?php ob_start();

php session timeout all code in one page

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

Logout problem /session not destroyed

I am having a problem when trying to login.. below is my code for the login
<?php
session_start();
include("functions.php");
connecttodb();
if(!empty($_SESSION['loggedin']) && !empty($_SESSION['username']))
{
echo "already logged in";
header("refresh:3; url=main.php");
}
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql="SELECT * FROM admin WHERE admin_username ='".$username."' AND admin_password= '".$password."'";
$result=mysql_query($sql) or die(mysql_error());
echo $sql;
if(mysql_num_rows($result) == 1)
{
$row = mysql_fetch_array($result);
$acc = $row['account'];
$_SESSION['username'] = $username;
$_SESSION['account'] = $acc;
$_SESSION['loggedin'] = 1;
echo "<h1>Success</h1>";
echo "<meta http-equiv='refresh' content='=2;panel.php' />";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Please click here to try again.</p>";
}
}
else
{
?>
<form method="post" action="login.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
My logout file
<?php
$_SESSION = array();
session_unset();
session_destroy();
echo "Logged Out !";
header("Location:login.php");
?>
The problem is that when i try to logout the session is not destroyed. When it redirects to the login page it says that im already logged in. How can i completely destroy the session when the users clicks on logout?
change your logout to the following:
<?php
session_start(); # NOTE THE SESSION START
$_SESSION = array();
session_unset();
session_destroy();
// echo "Logged Out!";
// Note: Putting echo "Logged Out!" before sending the header could result in a "Headers already sent" warning and won't redirect your page to the login page - pointed out by #Treur - I didn't spot that one.. Thanks...
header("Location:login.php");
exit(); # NOTE THE EXIT
?>
The session_start() is always require for each page when dealing with sessions.
Make sure you exit() the page when using header() with Location as the page will continue to execute.
I think you forgotten the session_start() before $_SESSION = array(); in your logout script

Categories