Asked in PHP Programming
PHP Programming

How do you write login and logout code in php?

91011

Answer

User Avatar
Wiki User
09/12/2011

Have a session_start(); at the very top of the page in php like this:

<?php

session_start();

?>

Then write a login form:

<form action="login.php" method = "POST">

<input type = "text" name = "username">

<input type = "password" name = "password">

<input type = "submit" value = "submit">

</form>

now start a new page called login.php. Put session_start(); at the top of the page again. Now you'll have two different $_POST variables from the form that got submitted. It's $_POST['username'] and $_POST['password']. the "name" of the input is what the $_POST variable is. And it's a $_POST because of the method of the form. Now you should change the names of the $_POST just to make it easier.

<?php

$username = $_POST['username'];

$password = $_POST['password'];

?>

Now it's time to see if that username and password are in the database

<?php

$mysql = "SELECT COUNT(*) FROM users WHERE username = '$username' AND password = '$password'"; // Select statement to find user

$query = mysql_query($mysql); // Query to see if user exists

$result = mysql_query($query); // Result for query. Should be either 1 or 0.

if ($result != 1)

{

?>

<script>

alert ("That username or password doesn't exist");

</script>

<meta http-equiv="refresh" content = "1; URL = index.php">

<?php // Javascript alert saying that username or password was wrong then loading the page back to the main page.

}

else

{

$_SESSION['username'] = $username; // Setting the variable for the username so now you can use $_SESSION['username'] anywhere on your website to display who is logged in.

}

?>

You have to put session_start(); at the top of every webpage though. Now for the logout. Create a page called logout.php. You can link to this page however you'd like. All you need for this page is:

<?php

session_destroy(); //destroys the current session

<meta http-equiv="refresh" content = "1; URL = index.php"> //Reloads the page back to the index.php

?>