I am new to programming. I need a simple login page code for PHP which displays an error message in the same page for incorrect login details and redirected to the account page incase of correct login details. The code should remember the activity and redirect to the account page of the user if he has closed the page without login out. Any help would be deeply appreciated.
Log in page
<html>
<head>
<title>Login</title>
</head>
<h3>Login Page</h3>
<form action="trylog.php" method = "post"><!--action redirects to trylog.php -->
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br /><!--username label defined -->
<label for="password">Password:</label> <input type="password" id="password" name="password"><br /><br /><!--password label defined -->
<button type = "submit">Login</button><!--submit button defined -->
</form>
</html>
Account page
<html>
<title>Login</title>
<body>
<?php
session_start(); //resumes previous session based on indentifiers from POST attribute in login.php
$usr = "admin"; //usr keyword defined
$psw = "password"; //psw keyword defined
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password"))
//checking for correctness of username and password
{
echo "password accepted";
$_SESSION['login']=true;
//successful login confirmation
echo "<br><a href='http://localhost/login/login.php'>Logout</a>";
}
else
{
echo "incorrect login";
//incorrect login message
}
session_destroy(); //destroys session
?>
</body>
</html>
Thanks Navaneeth
session_start
has to be before output, so move that before <html>
etc. (output is a space before <?php
too. <?php
has to be the first sequence in your code.
what you meant by $psw
and $usr
variables? You have them in form, delete them.
When you work with variables, don´t use quotes - you can use double-quotes marks, not single. Better is to use no quote marks: $username = $_POST['username'];
. On the other hand, the key should be in quote marks, elsewhere you work with undefined constant username
- if constant doesn´t exists, PHP work with the same string.
Condition on line 12 will never be true
because you test there a SESSION
which hasn´t been set before. You set this session on your line 16, but only if this session already exists (line 12). It´s logical nonsense :-)
Why you create variables $username
and $password
when you doesn´t work with them?
Before you work with $_POST
, lines 9 and 10, you must check if the form was sent, so if (isset($_POST['username'])) {}
.