User login using PHP can be performed in a very simple and the short code. We need the different following lines of code to make the login page.
We will create two input fields in HTML form and a submit button. One input for username with type 'text' or if username is of email type then type 'email'.
<form method="post">
<input type="email" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="login">
</form>
<?php
mysql_connect('localhost','root','');
mysql_select_db('database_name');
?>
If the forms submit then we will fetching the user with submitted respective username and password. If the respective user fetch then we will create PHP SESSION of user_id redirect to the certain URL and if the username or password is incorrect we will print an error message.
<form method="post">
<input type="email" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="login">
</form>
<?php
mysql_connect('localhost','root','');
mysql_select_db('database_name');
if($_POST['login'])
{
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT ! FROM users WHERE username='".$username."' AND
password='".$password."' ");
$user_rec = mysql_fetch_assoc($query);
if($user_exist) // Case Username and Password Valid
{
session_start();
$_SESSION['user_id'] = $user_exist['user_id']; // Setting Session
echo "Successfully Login";
header('Location: Dashboard.php'); //Redirecting
}
else{
echo " Incorrect Username/Password ! ";
}
}
?>