My code has two forms that create a text field for both username and password. The php script takes the form information and sends it to the server for it to decide if the strings from the form data correspond with the username and password I want. I also have a logout button form that goes to a logout.php script which logs the user out. If I click the logout button it sends the user to my login.php script and ends the session. I can’t get users to login to the website and I cant get users to go to the login.php page if I go to the site that has the logout.php. Here is my code:
Login php Code:
<?php
session_start();
if($_SESSION['login'] == true)
{
header("Location:index.php");
}
else
{
if($_POST['username'] == 'username')
{
if($_POST['pass'] == 'password')
{
$_SESSION['login'] = true;
header('Location:index.php');
}
}
}
?>
Login Form:
<form action="login.php" method="post">
Username: <input type="text" name="username" /> </br>
Password: <input type="password" name="pass" />
<input type="submit" value="submit"/>
</form>
Logout PHP code:
<?php
session_start();
session_destroy();
header('Location:index.php');
?>
index php code:
<?php
session_start();
if($_SESSION['login'] =! true || $_SESSION['login'] == "")
{
header('Location:login.php');
}
?>
index form code:
<form action="logout.php" method="post">
<input type="submit" name="logout" value="logout" />
</form>
The PHP code is listed above the html code before anything is displayed thus why some form actions call back the page again. Thank you
Your main problem is the incorrect operator
=!inindex.php— the correct use is!=for “does not equal”. See more: http://php.net/manual/en/language.operators.comparison.phpYou can clean up your login.php file a bit:
login.php
Your login form is fine, except where you use
:for properties. All HTML element properties arename="value"— note the equal sign. So your form:You have it correct in your logout form.
One of your goals is to reduce the amount of code you use. So if you’re going to do the same thing many times, you should try to isolate that piece of code as a class, a function, or simply in another file that you include. To that end, you could put your check for login in a separate file:
security.php
… then use
require_onceto pull that in on any page where you require the user to be logged in:index.php
Documentation
require_once– http://php.net/manual/en/function.require-once.php