Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logout PHP Script

Tags:

php

logout

This is my script:

<?php
  // If the user is logged in, delete the session vars to log them out
  session_start();
  if (isset($_SESSION['user_id'])) {
    // Delete the session vars by clearing the $_SESSION array
    $_SESSION = array();

    // Delete the session cookie by setting its expiration to an hour ago (3600)
    if (isset($_COOKIE[session_name()])) {      setcookie(session_name(), '', time() - 3600);    }

    // Destroy the session
    session_destroy();
  }

  // Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
  setcookie('user_id', '', time() - 3600);
  setcookie('username', '', time() - 3600);

  // Redirect to the home page
  $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
  header('Location: ' . $home_url);
?>

I cannot log out once logged in on the site. Do I really need cookie'd logins or can I take that out?

like image 667
user2544765 Avatar asked Jan 23 '14 22:01

user2544765


2 Answers

Try a simpler approach, destroy all session cookies

session_start();
session_destroy();
$home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
header('Location: ' . $home_url);
like image 102
Adam Brown Avatar answered Sep 19 '22 20:09

Adam Brown


I recommend to using this method,

<?php
//User session in ['user']
if($_SESSION['user_id']){
  session_start();
  session_unset();
  session_destroy();
  session_write_close();
  setcookie(session_name(),'',0,'/');
  session_regenerate_id(true);
}
?>

i recommend you using that method , why? because that method using true destroy,delete cookie in browser and new set ID of session of session in PHP

like image 30
Abdul Aziz Al Basyir Avatar answered Sep 17 '22 20:09

Abdul Aziz Al Basyir