How do I destroy a session in php?
the thing is when the user clicks the logout button the session will end and he will be redirected to the index.php here's my code
Customer.php
<?php
session_start();
#include("Connection.php");
if (isset($_POST['submit'])) {
$name = $_POST['customerName'];
$_SESSION['user'] = $name;
}
if (isset($_SESSION['user'])) { echo "Hello {$_SESSION['user']}, welcome back"; }
else{echo "walang tao";}
$sql="INSERT INTO ORDERS(Name) VALUES('$name')";
mysql_query($sql);
session_destroy();
?>
<button></button>
and this is from the index.php where the user wants to log in again
<?PHP
/* this must go before any html */
session_start();
if (isset($_SESSION['user'])) {
header("location: Customer.php");
}
?>
<div class="sign">
<h2>Welcome</h2>
<form action = "Customer.php" method = "POST">
Customer Name:<input type = "text" name="customerName">
<input type = "submit" name = "submit">
</form>
session_start();
session_destroy();
You may also used unset() function for free up session Environment.
if (isset($_SESSION['user']))
{
unset($_SESSION['user']);
header('location:index.php');
}
Include this file in your header and set the required settings in file.
It should work well.
<?php
session_cache_expire(20);
if (!isset($_SESSION)) {
session_start();
}
// set timeout period in seconds
$inactive = 1200; // timeout for the session
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) {
$_SESSION = array();
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
header("Location: index.php"); // or whatever you prefer to do.
}
}
$_SESSION['timeout'] = time();
?>
If you aren't using the auth component then its really easy
public function logout(){
$this->Session->destroy();
// no cake we really want you to delete it because you suck
$this->Session->destroy();
}
//If you want complete destroy session then you can write.
session_destroy();
The session_unset() //function frees all session variables currently registered.
Related
Whenever I run the logout.php script then go back to a page that is protected without login it will have me still logged in
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
exit();
?>
login.php
$userlogin = user_login($email, $password.$salt);
if ($userlogin==false){
$errors[]='Wrong email/password combination.';
} else {
//set the user session
$_SESSION['UserId']=$userlogin;
$_SESSION['LoginIP']=$_SERVER['REMOTE_ADDR'];
$db->query("UPDATE users SET ipadd='".$_SERVER['REMOTE_ADDR']."' WHERE user_id=".$_SESSION['UserId']."");
echo '<meta http-equiv="refresh" content="0; URL=index.php">';
Check logged in snippet
/* Check if user is logged in or not */
function loggedin(){
return (isset($_SESSION['UserId'])) ? true : false;
}
if (loggedin()==true){
$session_user_id = $_SESSION['UserId'];
$user_data = user_data($session_user_id,'full_name','username');
$rezult =$db->query("SELECT ipadd FROM users WHERE user_id=".$_SESSION['UserId']."");
while($rez = $rezult->fetch_assoc()){
if ($rez['ipadd']==$_SERVER['REMOTE_ADDR']) {
} else {
echo '<meta http-equiv="refresh" content="0; URL=logout2.php">';
}
}
}
Been look at posts with the same question but whatever I try still getting the same issue. Any advice would be extremely appreciated!
this is from php.net http://php.net/manual/en/function.session-destroy.php
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
so you just need $_SESSION = null, and logout should happen.
I think in your index.php file should have these line:
if(!isset($_SESSION["session_name"])){
header("Location: somewhere_mainpage.php");
}
It is better to make all pages have these line. These line will send header to another page if no session has started.
I believe that session_start(); function call should be on your login page when the user login data is correct, and in your logout PHP code, you should set
session_destroy(); or unset($_SESSION['UserId'];
Logout.php:
<?php
session_destroy();
/* * OR * */
//unset($_SESSION['UserId'];
header("Location: ../index.php");
exit();
?>
<?php
session_unset();
session_destroy();
header("Location: ../index.php");
?>
should work, otherwise you could unset the values
<?php
unset($_SESSION['UserId']); // Unsets the UserId Variable reuse for each variable
session_destroy();
header("Location: ../index.php");
?>
have you tried just session_destroy() ?
also I'm not sure wether you need session_start() when you are closing the session, from memory you only need it to start the session
I always like to destroy the server session, and client cookie, try to manually cover all options in case of any errors.
You can destroy the cookie in PHP with:
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly );
<?php
$cookie_path = "...";
$cookie_domain = "...";
$cookie_secure = "...";
$cookie_httponly = "...";
session_start();
session_unset();
session_destroy();
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain,$cookie_secure, $cookie_httponly );
header("Location: ../index.php");
exit();
time() - 3600 makes the cookie expiry before the current time, which makes it invalid.
Another option to investigate is session_regenerate_id() on your logout pages. Some reference pages are below:
php.net - session-regenerate-id
https://stackoverflow.com/a/22965580/1246494
I have built a login page using php and pdo and created and logged in properly but after clicking log out button if I click back again it again goes to my page which appear only if logged in I even used session but it is not running properly even
<?php
include('connect.php');
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
if(isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$errflag = false;
if($username == '' and $password == '') {
echo "you must enter username and password";
$errflag = true;
}
if ($errflag == false) {
SignIn($username,$password);
}
}
function SignIn($username,$password){
global $connect;
$search = $connect->prepare("SELECT * FROM users where username =
:username AND password = :password ");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$search->execute();
$count = $search->rowCount();
if($count> 0)
{
$_SESSION['username'] = $_POST['username'];
if(!isset($_SESSION['logged_in']))
header("Location: myfile.php");
}
else{
echo "wron email or password";
}
}
?>
the code of inner page is
<?php
echo "welcome to the website ";
echo "congrats you are logged in ";
?>
<html>
<head>
<title>
welcome here</title>
</head>
<body>
<form method ="POST" action = "login.php">
<button name="logout" style="float:right;">logout</button>
</form>
<h1><center>google is one of the best search engine</center></h1>
</body>
</html>
thankyou I updated the in the above manner but it is not working
Add bit of code session_start(); at the beginning of the page.
<?php
session_start();
if(isset($_POST['logout'])){
{
unset($_SESSION['logged_in']);
session_destroy();
header("location:index12.php");
}
}
?>
Also if you have not start session in connect.php ,you must need to start session by using session_start();
<?php
session_start();
include('connect.php');
I don't know how do you start your session but this a suggestion:
I generally write a new_session() function which looks like the following. I do prefer to set cookie params so we can have some control over it.
function new_session()
{
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $cookieParams['domain'], Sessions::SECURED_COOKIES, Sessions::HTTP_ONLY);
session_name('My_Awesome_App');
session_start();
session_regenerate_id();
}
And another one to destroy everything
function destroy_session()
{
session_unset();
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
session_destroy();
}
You can find the documentation about session_get_cookie_params() here
and about session_set_cookie_params() here
Back to your example
Using this new function you should call new_session() on top of your pages and your logout should look like.
new_session();
if (isset($_POST['logout'])) { {
unset($_SESSION['logged_in']);
destroy_session(); // our new function
header("location:index12.php");
}
}
I tried a login and logout function in a signin bootstrap theme and it worked fine. But am not able to logout the session in my other tenplate when I use the same code which I used previously which worked. I tried all most all the solutions found in internet. I am getting a blank page when I click on Logout link.
login.php
<?php
session_start();
if (!empty($_SESSION['login_user'])) {
header('location:index.php');
}
?>
---html code---
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'foodchain');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myusername = mysqli_real_escape_string($db,$_POST['email']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$sql = "SELECT email,password FROM user_register WHERE email='$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQL_ASSOC);
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header('Location:index.php');
}else {
$logmsg = "Invalid Username or Password";
}
}
?>
check_login.php
<?php
session_start();
if (!isset($_SESSION['login_user']) || empty($_SESSION['login_user'])) {
header('location:login.php');
}
?>
logout.php
<?php
session_start();
session_destroy();
header("Location:login.php");
die();
?>
index.php
<?php
include('check_login.php');
?>
Its perfectly working when I don't use the template(downloaded from some website), or when I use the bootsrap signin template.
You really should provide us with some source code, links to things that you've tried, what you've previously tried, what errors you received, etc. From what I can gather, you're looking for a logout page using sessions? Here's what I've got.
<?php
session_start();
session_destroy();
header('Location: ..');
?>
The key part is setting $_SESSION to an empty array.
From http://php.net/manual/en/function.session-destroy.php:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
I'm trying to create a simple member login site, and I was following along with a tutorial online. However, a deprecated function is used. Here is the code.
<?php
session_start();
session_destroy();
if(isset($_COOKIE['id']))
{
//remove cookie
setcookie("$id_cookie", '', time() - 50000);
setcookie("$pass_cookie", '', time() - 50000);
}
if(!session_is_registered('username'))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>
I also tried !isset($_SESSION['username']), but every time I try to log out, I just receive the 'Sorry we could not log you out' text.
Here is the part of my login.php file code where I set the sessions:
//member does exist, start sessions
$_SESSION['password'] = $password;
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
Any help would be great!
Don't use
session_is_registered
use
if (isset($_SESSION['SESSION_VARIABLE_NAME']))
You may add "session_unset();" before "session_destroy();"
session_destroy() delete the session file and release the session id, but keep the $_SESSION variable in memory.
use this with isset
if(!isset($_SESSION['username']))
Try this
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
Check where the the SESSSION is stored or not.
Try this code in your log out script
<?php
session_start();
if(isset($_SESSION['id']))
{
unset($_SESSION['username']);
unset($_SESSION['id']);
}
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>
My problem may seem pretty elementary, but I dont know whats wrong with my code. I have a very simple login system that looks like this:
login.php:
<?php
session_start();
if ($_SESSION['loggedin'] = 1) {
header("Location: admin.php");
}
if ($_GET['login']) {
// Only load the code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['username'] == 'thenemis'
&& $_POST['password'] == 'slustice') {
// Load code below if both username
// and password submitted are correct
$_SESSION['loggedin'] = 1;
// Set session variable
header("Location: admin.php");
exit;
// Redirect to a protected page
} else echo "Wrong details";
// Otherwise, echo the error message
}
?>
<form action="?login=1" method="post" accept-charset="utf-8">
<fieldset>
<label for="username">Usermame:</label>
<input type="text" name="username" placeholder="username" required>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="password" required>
<input type="submit" value="Login"> </td>
</fieldset>
</form>
This works fine.
admin.php:
<?php
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['loggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: login.php");
exit;
}
?>
<p>Log out</p>
Now my problem is, that the system keeps me logged even though i clicked the logout URL, which looks like this:
logout.php:
<?php
session_start();
session_destroy();
header("Location: login.php");
?>
There is obviously some elementary mistake with my logout procedure, but I cant seem to find it... Thanks for any help in advance!
You are making assignment here:
if ($_SESSION['loggedin'] = 1) {
header("Location: admin.php");
}
and you should make comparisment
if ($_SESSION['loggedin'] == 1) {
header("Location: admin.php");
}
Try this
<?php
session_destroy();
header('Location: index.php');
exit();
?>
change your admin.php file
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
}
?>
<p>Log out</p>
In login.php you didn't started session_start after user details verified...
try to add session_start(); before $_SESSION['loggedin'] = 1;
This may work for you...
in logout.php
before estroying unset the session variable
using this line
unset($_SESSION['loggedin']);
From the php.net Manual:
In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
Use this code (copied from php.net) to logout securely:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
Just try with the following changes :
In login.php :
if ($_SESSION['loggedin'] == 1) {
header("Location: admin.php");
}
In logout.php :
<?php
session_start();
ob_start();
session_destroy();
$_SESSION['loggedin']=""; //Just empty that session variable
header("Location: login.php");
?>
I think this may help you to resolve your problem.