how do I "logout" using php?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
doug76
Forum Commoner
Posts: 26
Joined: Tue Aug 24, 2010 7:44 am

how do I "logout" using php?

Post by doug76 »

have been wrestling this problem for about a week with limited success.
I have set up a password protected area using PHP where users can login and view their and other details.
I am trying to set up a feature where they can also logout at will and this has me stumped. For some reason it can be done by going into "editprofile1" and clicking on "save" and then clicking on "Logout" and apart form the error message " Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in C:\Program Files (x86)\EasyPHP5.2.10\www\editprofile1.php on line 91" when I click on long out I am successful. Any other way just returns me to the “index2” page as specified in the code but no other action takes place. As the code used and destination the same how can one way work and not other? Any help would be most gratefully appreciated.
I am using local host and code is below.
If any more information is required please ask and I will provide.
I apologise in advance for the legnth of the code
[Never mind apologizing, learn to use the PHP Code button in the post editing screen to surround your code so we can read it, as I have done for you here.]
editprofile.php

Code: Select all

<?php
  
session_start();

  
// If the session vars aren't set, try to set them with a cookie
  
if (!isset($_SESSION['user_id'])) {
    if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
      $_SESSION['user_id'] = $_COOKIE['user_id'];
      
$_SESSION['username'] = $_COOKIE['username'];
    
}
  }

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  
<title>Mismatch - Edit Profile</title>
  
<link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body>
  
<h3>Mismatch - Edit Profile</h3>


<?php
  
require_once('appvars1.php');
  require_once('connectvars1.php');

  
// Make sure the user is logged in before going any further.
  
if (!isset($_SESSION['user_id'])) {
    echo '<p class="login">Please <a href="login.php">log in</a> to access this page.</p>';
    
exit();
  
}
  else {
    echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. <a href="logout1.php">Log out</a>.</p>');

  }


  // Connect to the database
  
$dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name);

  
if (isset($_POST['submit'])) {
    

// Grab the profile data from the POST
    
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
    
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
    
$gender = mysqli_real_escape_string($dbc, trim($_POST['gender']));
    
$birthdate = mysqli_real_escape_string($dbc, trim($_POST['birthdate']));
    
$city = mysqli_real_escape_string($dbc, trim($_POST['city']));
    
$state = mysqli_real_escape_string($dbc, trim($_POST['state']));
    
$old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture']));
    
$new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name']));
    
$new_picture_type = $_FILES['new_picture']['type'];
    $new_picture_size = $_FILES['new_picture']['size']; 
    
list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']);
    
$error = false;

    

// Validate and move the uploaded picture file, if necessary
    
if (!empty($new_picture)) {
      if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
        ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
        ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
        if ($_FILES['file']['error'] == 0) {
          

// Move the file to the target upload folder
          
$target = MM_UPLOADPATH . basename($new_picture);
          
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
            

// The new picture file move was successful, now make sure any old picture is deleted
            
if (!empty($old_picture) && ($old_picture != $new_picture)) {
              @unlink(MM_UPLOADPATH . $old_picture);
            }
          }
          else {
            

// The new picture file move failed, so delete the temporary file and set the error flag
            
@unlink($_FILES['new_picture']['tmp_name']);
            
$error = true;
            echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';

          }
        }
      }
      
else {
        
// The new picture file is not valid, so delete the temporary file and set the error flag
        
@unlink($_FILES['new_picture']['tmp_name']);

        $error = true;
        
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
          ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
      }
    }

    

// Update the profile data in the database
    
if (!$error) {
      if (!empty($first_name) && !empty($last_name) && !empty($gender) && !empty($birthdate) && !empty($city) && !empty($state)) {
        // Only set the picture column if there is a new picture
        if (!empty($new_picture)) {
          $query = "UPDATE mismatch_user SET first_name = '$first_name', last_name = '$last_name', gender = '$gender', " .
            " birthdate = '$birthdate', city = '$city', state = '$state', picture = '$new_picture' WHERE user_id = '" . $_SESSION['user_id'] . "'";
        }


        else {
          
$query = "UPDATE mismatch_user SET first_name = '$first_name', last_name = '$last_name', gender = '$gender', " .
            " birthdate = '$birthdate', city = '$city', state = '$state' WHERE user_id = '" . $_SESSION['user_id'] . "'";
        }
        mysqli_query($dbc, $query);

        

// Confirm success with the user
        
echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile1.php">view your profile</a>?</p>';

        
mysqli_close($dbc);
        exit();
    
  }
      
else {
        echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>';
   
   }
    }
  } 

// End of check for form submission
  else {
    

// Grab the profile data from the database
    
$query = "SELECT first_name, last_name, gender, birthdate, city, state, picture FROM mismatch_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
    
$data = mysqli_query($dbc, $query);
    
$row = mysqli_fetch_array($data);

    
if ($row != NULL) {
      $first_name = $row['first_name'];
      
$last_name = $row['last_name'];
      $gender = $row['gender'];
      
$birthdate = $row['birthdate'];
      $city = $row['city'];
      
$state = $row['state'];

      $old_picture = $row['picture'];
    
}
    else {
      echo '<p class="error">There was a problem accessing your profile.</p>';

    }
  }


  mysqli_close($dbc);

?>

  
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" />
    
<fieldset>
      <legend>Personal Information</legend>
      <label for="firstname">First name:</label>
      <input type="text" id="firstname" name="firstname" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br />

      <label for="lastname">Last name:</label>
      <input type="text" id="lastname" name="lastname" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br />
      <label for="gender">Gender:</label> <select id="gender" name="gender">
        <option value="M" <?php if (!empty($gender) && $gender == 'M') echo 'selected = "selected"'; ?>>Male</option>
        <option value="F" <?php if (!empty($gender) && $gender == 'F') echo 'selected = "selected"'; ?>>Female</option>
      </select><br />


      <label for="birthdate">Birthdate:</label>
      <input type="text" id="birthdate" name="birthdate" value="<?php if (!empty($birthdate)) echo $birthdate; else echo 'YYYY-MM-DD'; ?>" /><br />


      <label for="city">City:</label>
      <input type="text" id="city" name="city" value="<?php if (!empty($city)) echo $city; ?>" /><br />
      <label for="state">State:</label>
      

<input type="text" id="state" name="state" value="<?php if (!empty($state)) echo $state; ?>" /><br />
      

<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
      <label for="new_picture">Picture:</label>
      <input type="file" id="new_picture" name="new_picture" />
      <?php if (!empty($old_picture)) {
        echo '<img class="profile" src="' . MM_UPLOADPATH . $old_picture . '" alt="Profile Picture" />';
      } 
?>
    
</fieldset>
    
<input type="submit" value="Save Profile" name="submit" />
  
</form>

</body> 

</html>
logout1.php

Code: Select all

<?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']) . '/index2.php';
  

header('Location: ' . $home_url);



?>
index2.php

Code: Select all

<?php
  session_start();

  
// If the session vars aren't set, try to set them with a cookie
  
if (!isset($_SESSION['user_id'])) {
    if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
      
$_SESSION['user_id'] = $_COOKIE['user_id'];
      
$_SESSION['username'] = $_COOKIE['username'];
    }
  }

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  
<title>Mismatch - Where opposites attract!</title>
  
<link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body>
  
<h3>Mismatch - Where opposites attract!</h3>


<?php
  require_once('appvars1.php');
  
require_once('connectvars1.php');

  
// Generate the navigation menu
  
if (isset($_SESSION['username'])) {
    
echo '&#10084; <a href="viewprofile1.php?<?php echo SID; ?>">View Profile</a><br />';
    
echo '&#10084; <a href="editprofile1.php?<?php echo SID; ?>">Edit Profile</a><br />';
    
echo '&#10084; <a href="logout1.php?<?php echo SID; ?>">Log Out (' . $_SESSION['username'] . ')</a>';
  
}
  
else {
    echo '&#10084; <a href="login4.php">Log In</a><br />';
    
echo '&#10084; <a href="signup.php">Sign Up</a>';
  }

  
// Connect to the database 
  
$dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); 

  
// Retrieve the user data from MySQL
  
$query = "SELECT user_id, first_name, picture FROM mismatch_user WHERE first_name IS NOT NULL ORDER BY join_date DESC LIMIT 5";
  
$data = mysqli_query($dbc, $query);

  
// Loop through the array of user data, formatting it as HTML
  
echo '<h4>Latest members:</h4>';
  
echo '<table>';
  
while ($row = mysqli_fetch_array($data)) {
    if (is_file(MM_UPLOADPATH . $row['picture']) && filesize(MM_UPLOADPATH . $row['picture']) > 0) {
      echo '<tr><td><img src="' . 

MM_UPLOADPATH . $row['picture'] . '" alt="' . $row['first_name'] . '" /></td>';
   
 }
    
else {
      echo '<tr><td><img src="' . MM_UPLOADPATH . 'nopic.jpg' . '" alt="' . $row['first_name'] . '" /></td>';
    }
    
if (isset($_SESSION['user_id'])) {
      echo '<td><a href="viewprofile1.php?user_id=' . $row['user_id'] . '">' . $row['first_name'] . '</a></td></tr>';
  
  }
    else {
      echo '<td>' . $row['first_name'] . '</td></tr>';
    }
  }
  echo '</table>';

  
mysqli_close($dbc);

?>

</body> 

</html>
Last edited by califdon on Sun Sep 05, 2010 5:16 pm, edited 2 times in total.
Reason: Enclose code in [syntax=php] tags
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: how do I "logout" using php?

Post by califdon »

I won't even address your error in editprofile1.php, since I don't understand what you are saying, but it looks to me like logout1.php should work. What do you mean when you say "no other action takes place"? Have you verified that the session is still active? Can you logout, then get back into protected area without logging back in?

What I see is that you ARE executing the logout1.php script, since it is returning you to index2.php, and I don't see anything wrong in your code, so I can't see how your session is remaining active. What tells you that it is?
john4u
Forum Newbie
Posts: 3
Joined: Sat Sep 04, 2010 2:45 pm

Re: how do I "logout" using php?

Post by john4u »

Hi,

Use this for 100% success

write this code in your logout page thats it

<?php
session_start();
session_destroy();
echo "<script>window.location.href='index.php'</script>";
exit();

?>

Thanks,
John
speed.prateek@gmail.com
doug76
Forum Commoner
Posts: 26
Joined: Tue Aug 24, 2010 7:44 am

Re: how do I "logout" using php?

Post by doug76 »

Thanks both. I will learn to use the PHP Code button. Sorry I'm still fairly new.
Further clarification.
If the user clicks on "logout" in index2.php it looks as though nothing happens. It is the same effect as refreshing the page. I know it goes to the logout1.php but only seems to act only on the redirect.
I know the session is active as I can logout in the other way: editing an entry and saving then logging out in editprofile1.php.
The menu should change if I logout successfully but it doesn't at the moment.
Does this make thing clearer?
Any ideas/ help as always much appreciated
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: how do I "logout" using php?

Post by califdon »

It appears that the user cookies are the problem. Your logout1.php is destroying the session and the user cookies, but when it redirects you to index2.php, that is re-establishing a session, using the user_name and user_id from the cookies, which should have been destroyed, but it looks like only the session_name cookie is being set to a past time in logout1.php.

Try this: in logout1.php, replace this code

Code: Select all

if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '', time() - 3600);
    }
with this code:

Code: Select all

if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '', time() - 3600);
      setcookie(username(), '', time() - 3600);
      setcookie(user_id(), '', time() - 3600);      
    }
doug76
Forum Commoner
Posts: 26
Joined: Tue Aug 24, 2010 7:44 am

Re: how do I "logout" using php?

Post by doug76 »

Unfortunately that doesn't seem to work. I get the following error:
Fatal error: Call to undefined function username() in C:\Program Files (x86)\EasyPHP5.2.10\www\logout1.php on line 20

Could this be something to do with how my php is set up? I am in localhost
doug76
Forum Commoner
Posts: 26
Joined: Tue Aug 24, 2010 7:44 am

Re: how do I "logout" using php?

Post by doug76 »

I have sorted it. The code was correct but I mistakenly added an extra "/" to the address. Thanks for all responses
Post Reply