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','');
Related
i am developing a log in form with session. When i log in and try to change page in the same domain and get back to login page, i am logged out and credentials needed. Bellow is the code.
mysky.php (login page)
<?php
session_start();
$pageTitle = 'MySky Login';
include 'header.php';
?>
<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>
<form action="myskyweb.php" name="form" method="POST"
onsubmit="return IsEmpty();">
<div id="msg"><?php if(isset($msg)) { echo $msg; }?></div>
<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>
<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>
<button id="btn" type="submit">Login</button>
</form>
</div>
<?php include 'footer.php';?>
myskyweb.php (after successfull login)
<?php
session_start();
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
}
$pageTitle = sprintf('MySky - %s', $_POST['user']);
include 'header.php';
include 'login.php';
?>
<?php
print_r($_SESSION);
?>
<div id="logout">Logout</div>
<?php include 'footer.php';?>
page1.php (one page of my domain)
<?php
session_start();
$pageTitle = 'page1';
include 'header.php';
?>
<?php
print_r($_SESSION);
?>
<div id="structure">
<?php include 'footer.php';?>
page2.php (another page)
<?php
session_start();
$pageTitle = 'page2';
include 'header.php';
?>
<?php
print_r($_SESSION);
?>
<div class="slides">
<?php include 'footer.php';?>
login.php (checking if credentials are correct & give value to session)
<?php
include 'db_info.php';
$username = $password = $encrypted = $msg = '';
//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);
//get values
$username = $_POST['user'];
$password = $_POST['pass'];
//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
//encrypt pass
$encrypted = md5($password);
//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));
//compare
$row = mysqli_fetch_array($result);
if (($row['username'] == $username) && ($row['password'] == $encrypted)){
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
$_SESSION['logged_in'] = time();
} else {
$msg = 'Credentials mismatch';
header("Location: /mysky.php");
die();
}
mysqli_close($conn);
?>
I used the function print_r() at all of the pages to understand if the problem is the session. Session is not the problem, because after log in every page shows the sessions var. So session keep the values after changing a page. I cannot undestand why i see login form in login page again rather to see successfull login page.
Any help is appreciated!
You'll need to assign a $_SESSION variable when they are logged in. Take a look at my example below
Login.php
//login code
.....
//
//if successful
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
And then at the top of your subsequent pages for example..
home.php
<?php
session_start();
if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
echo 'blah'
?>
if you want to remove the login button or redirect if they try to
access the login page you'd need to do some handling to implement
this.
Change login button -> logout button
<?php if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
?>
<li> <a href="logout.php"> Logout | <?php echo
$_SESSION['user_id'] ?> </a></li>
<?php }else{ ?>
<li> <a href="loginpage.php" >login</a></li>
<?php } ?>
Protected.php
<?php
session_start();
if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){
echo "Oops, you're not supposed to be here\n";
echo 'You\'ll be redirected in 5 seconds. If not, click here.';
header( "refresh:5;url=index.php" );
exit;
}
echo 'Congratulations! You are logged in!';
echo 'You\'ll be redirected in 5 seconds. If not, click here.';
header( "refresh:5;url=index.php" );
die();
?>
I believe this is everything you want to achieve, just change variables as required
EDIT 1
I can successful login but if then click to menu page1.php and then
click to mysky.php, i see the login form again and not the
myskyweb.php (authorized page)
OK - this is important. So your issue is not logging in, right? But, after authenticating, if you go back to log in page, you see the login form and you are not redirected. You want to automatically be redirected to the landing page if you are already authenticated. Is that right?
If so, then my question is, where in mysky.php (login page) are you checking if the user is logged in? I don't see that check anywhere.
You need to:
<?php
session_start();
// If the user is already logged in, redirect them to the landing page.
if (isset($_SESSION['id'])) {
header("Location: myskyweb.php");
}
You are only calling login.php after checking if the session variable id is set. That is why it is redirecting you back to the login page. Move that include up, directly under session_start(). The only reason that it sometimes works is that there is an existing session - see my next point.
myskyweb.php (after successfull login)
<?php
session_start();
// Move this include up here before the check.
include 'login.php';
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
}
$pageTitle = sprintf('MySky - %s', $_POST['user']);
include 'header.php';
...
?>
Also, for debugging purposes, clear the session each time you hit the log in screen. That way you'll not be confused about stale session data keeping you logged in
mysky.php (login page)
<?php
// Always clear the session when hitting the log in page.
session_destroy();
$_SESSION = [];
...
You're wide open to SQL Injection attacks - look up parameterized queries.
You need to call die; after issuing a header call - https://stackoverflow.com/a/768472/296555
#waterloomatt & #Isaac thanks for your time and responses! After so many hours, finally i found the code that works. If you see anything wrong, i would be happy to know!
Will i have problems with SQL Injection attacks?
login.php
<?php
session_start();
include 'db_info.php';
//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);
//get values
if ((isset($_POST['user'])) && (isset($_POST['user']))){
$username = $_POST['user'];
$password = $_POST['pass'];
} else {
$username = null;
$password = null;
}
//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
//encrypt pass
$encrypted = hash('sha256', $password);
//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));
//compare
$row = mysqli_fetch_array($result);
if (($row['username'] != $username) || ($row['password'] != $encrypted)){
if ((isset($_POST['user'])) && (isset($_POST['pass']))){
$_SESSION['msg'] = 'Credentials mismatch';}
} else {
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
}
mysqli_close($conn);
?>
mysky.php
<?php
include 'login.php';
if ((isset($_SESSION['id'])) && (isset($_SESSION['user'])))
{
include 'sky_auth.php';
}
else
{
include 'sky_login.php';
}
include 'footer.php';
?>
sky_login.php
<?php
$pageTitle = 'MySky Login';
include 'header.php';
?>
<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>
<form action="" name="form" method="POST" onsubmit="return IsEmpty();">
<div id="msg"><?php if (isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION);
session_destroy();} ?>
</div>
<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>
<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>
<button id="btn" type="submit">Login</button>
</form>
</div>
sky_auth.php
<?php
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
die();
}
$pageTitle = sprintf('MySky - %s', $_SESSION['user']);
include 'header.php';
?>
<div id="sky_contain">
<div id="logout">Logout</div>
</div>
</div>
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?
My session_start code on index.php
session_start();
if (isset($_SESSION['username'])){
session_id();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if (password_verify($password, $row[0])){$passwordOK = true;}
if($usernameOK == true && $passwordOK == true){
$_SESSION['username'] = $username;
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
Not really sure what your code does, because I dont see anything regarding setting the username or anything of that sort. What your code does is, it starts the session and checks if username variable in session is set, and if YES, it calls session_id.
Can you use this to check if the session is created properly?
session_start();
if (session_status() !== PHP_SESSION_NONE)
{
echo session_id();
}
Starts a session and shows you the session ID if the session_status is not PHP_SESSION_NONE
You don't need to do a session_id() to start a session, session_start() is enough.
I've tested the following on Safari on iPhone 6 (just add the db query part back if you want):
testa.php
<?php
//require('config.php');
session_start();
echo "Session ID: ".session_id()." <br>\n";
$usernameOK = false;
$passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernameOK = true;
$passwordOK = true;
if ($usernameOK == true && $passwordOK == true) {
$_SESSION['username'] = $username;
} else {
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])) {
header("Location: ../");
exit;
} else {
?>
<form class="login-form" method="POST">
<?php if (isset($error_message)) { ?>
<div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
testb.php
<?php
session_start();
echo "Session ID: ".session_id()." <br>\n";
echo "Data stored in session: {$_SESSION['username']}<br>\n";
Clear data/cookies on your mobile browser (or just go into incognito mode). This will make sure you "start from scratch".
Open testa.php on your mobile browser. Take note of the session id shown. Enter your login details and tap Submit. The next page may show blank.
Open testb.php. Again, take note of the session id shown. It should be equal to the session id shown in test1.php. If they are different then it is possible your mobile browser is configured not to accept cookies.
I've personally tested this on Safari on iPhone 6 and I was able to get the username data from session.
PS. A friendly reminder: don't forget to escape the data you use in queries (i.e. $username and $password). Use mysqli_real_escape_string, or use prepared statements. For security.
Maybe you are experiencing some conflict issues:
My session_start code
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if($usernameOK == true && password_verify($password, $row[0])){
if (isset($_SESSION)){
$_SESSION['username'] = $username;
} else{
session_start();
$_SESSION['username'] = $username;
}
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
In the index.php on the first line I have -> REMOVE THAT, PUT FIRST ROUTINE OF SESSION CHECKING
if (!isset($_SESSION)){
session_start();
}
EDIT: I noted that you're using header function to redirect to the index page. It's important avoid such redirects unless you're sending user out of your system, because some environments doesn't work well with them. I suggest to change your routine to user POST/GET http routines instead:
Inside validateSession.php
outside validateSession, NOTHING about sessions rules, concentrate everything there
index.php/head.php/some code that always starting in every page start only that:
<?php
include_once('validateSessions.php');
?>
Your form:
<form class="login-form" action="index.php" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
EDIT: I reviewed your routine, pay attention on validateSessions.php, I was forgetting to load session_start() in every routine that called the file. Put validateSessions inside your include directory.
UPDATE: Even my code helping the OP, the main problem was the SESSION configuration into php.ini file with session.save_path, causing issues about session routines. The php.ini fix solved the problem, the code I expect that helped OP to think about some routines towards Session stuff.
Probably your session is not set. Depending on the PHP version you use, check your session.
For versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
Cookies definitely work on mobile browsers.
I have simplified the code and the session is started when all checks are passed.
<?php
require('config.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($result);
if($usernameTEST == 1){
$row = mysqli_fetch_row($result);
if(password_verify($password, $row[0])) {
session_start();
$_SESSION['username'] = $username;
header("Location: ../");
exit();
}
}
$error_message = "Incorrect login data";
}
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.
<?php
$username = "Umesh";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
?>
In index.php you're trying to check the session status. The code is below.
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
print_r($_SESSION);
The above works for me on every browser and device. I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.
I verified that print_r ($_SESSION) was same in both cases.
Why you use session_id(). session I am always use this login system. I have no problem Desktop or Mobile session.
PHP code
<?php
session_start();
include 'connect.php';
if(isset($_POST['submit']))
{
$username = htmlspecialchars($_POST["uname"], ENT_QUOTES, "ISO-8859-1");
$username = stripslashes($username);
$password = htmlspecialchars($_POST["pass"], ENT_QUOTES, "ISO-8859-1");
$password = stripslashes($password);
$sql="SELECT * FROM member WHERE username= '$username' AND password='$password' AND status='1' ";
$result=mysql_db_query($dbname,$sql);
$row=mysql_fetch_row($result);
$num=mysql_num_rows($result);
$msg= "<h3 style='padding:0px;margin:0px;font-size:16px;background:#fff;padding:8px;'><font color='red'><center>Incorrect login data</center></font></h3>";
if($num>0)
{
$_SESSION['id'] =$row[0];
$_SESSION['fullName'] =$row[1];
$_SESSION['username'] =$row[2];
$_SESSION['password'] =$row[3];
$_SESSION['email'] =$row[4];
$_SESSION['userType'] =$row[5];
$_SESSION['status'] =$row[6];
header('location:index.php');
}
}
?>
My HTML Form
<form method="post">
<p><?php if (isset($_POST['submit'])) { echo $msg; } ?> </p>
<div>
<input type="text" name="uname" class="form-control" placeholder="Username..." required="" />
</div>
<div>
<input type="password" name="pass" class="form-control" placeholder="Password..." required="" />
<p align="right">Forgot it?</a></p>
</div>
<div>
<button class="btn btn-success submit" type="submit" name="submit"> Login <i class="fa fa-sign-in"></i></button>
</div>
</form>
Remove session_start(); in index.php
and Add this in your config.php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.
Also i tried executing the code by putting static value as username as follows
login.php
<?php
$username = "deadlock";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
index.php
<?php
if (isset($_SESSION['username'])){
session_regenerate_id(true);
} else if (!isset($_SESSION)){
session_start();
}
print_r(session_id());
I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards
Check that session_start() is placed before any browser output. I have found that Chrome on Desktop can be a lot more forgiving then other browsers as well as Mobile Chrome
This problem is generated with Chrome "Lite Mode" to reduce data load throw the Phone. If you use secret navigation so the lite mode is automatically disable an page work correctly. You have to disable "Lite Mode" on Chrome.
This is the final solution.
My problem was on server-side the session.save_path not definied to my server. Thanks a lot to all, who helped me :)
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 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