PHP Tutorial
Loading

Authentication with PHP and SQL

In this lesson, you will learn the basic concept of authentication with PHP.

Lesson Goals

  • To authenticate users with a login form.

Lesson Activities

  1. A Database-less Login Form

A Database-less Login Form

Below is a simple login form that uses a hard-coded username and password.

Code Sample:

Authentication/Demos/SimpleLogin.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<?php
	require 'Includes/Header.php';

	$msg='';
	$email = '';
	if (array_key_exists('LoggingIn',$_POST))
	{
		$email = $_POST['Email'];
		$pw = $_POST['Password'];
		if ($email == '[email protected]' && $pw == 'cowboy')
		{
			echo '<div align="center">Success</div>';
		}
		else
		{
			echo '<div align="center">Login Failed</div>';
			unset($_POST['LoggingIn']);
		}
	}

	if (!array_key_exists('LoggingIn',$_POST))
	{
?>

<div align="center">

	<h2>Log in</h2>
	<form method="post" action="SimpleLogin.php">
	<input type="hidden" name="LoggingIn" value="true">
		<table>
		<tr>
			<td>Email:</td>
			<td><input type="text" name="Email"
					value="<?php echo $email?>" size="25"></td>
		</tr>
		<tr>
			<td>Password:</td>
			<td>
			<input type="password" name="Password" size="10">
			</td>
		</tr>
		<tr>
			<td align="right" colspan="2">
			<input type="submit" value="Log in">
			</td>
		</tr>
		</table>
	</form>
</div>
<?php
	}
	require 'Includes/Footer.php';
?>
</body>
</html>

This page contains an HTML login form, which submits to itself (i.e, the action points to the same page). A hidden field, LoggingIn, is passed to the server when the user submits the form. The script checks to see if LoggingIn exists in the $_POST array. If it does, it processes the form input:

$email = $_POST['Email'];
$pw = $_POST['Password'];
if ($email == '[email protected]' && $pw == 'cowboy')
{
	echo '<div align="center">Success</div>';
}
else
{
	echo '<div align="center">Login Failed</div>';
	unset($_POST['LoggingIn']);
}

This code simply checks to see if the user's email and password match the hard-coded values ([email protected] and cowboy). If they do, it outputs a "success" message. If they don't, it outputs a "failed" message and removes LoggingIn from the $_POST array, so that the form will be displayed again.

Continue to the next lesson on Regular Expressions »

This page was last updated on 2022-05-20

All pages and graphics in this PHP Tutorial is copyright 2013 and are the property of learnphp-tutorial.com unless otherwise specified. The purpose of this website is to help you learn PHP on your own and use of the website implies your agreement to our Terms of Service.