ctt1010
11-01-2014, 02:25 PM
In this tutorial, we will use what we learnt from previous lessons to create our own basic PHP login system, which can be implemented anywhere. In this one we won't use MySQL to store the data, we'll use some predefined variables.
We will use 3 files here: the protected.php, after logging in; the login.php, the page to login.
Here is the login.php
<?php
session_start();
if ($_GET['login']) {
// Only load the code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['username'] == 'USERNAME'
&& $_POST['password'] == 'PASSWORD') {
// Load code below if both username
// and password submitted are correct
$_SESSION['loggedin'] = 1;
// Set session variable
header("Location: protected.php");
exit;
// Redirect to a protected page
} else echo "Wrong details";
// Otherwise, echo the error message
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="?login=1" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" />
</form>
</body>
And the protected.php page :
<?php
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['loggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: login.php");
exit;
}
?>
PROTECTED STUFF HERE (HTML/PHP)
Thank-you for reading this tutorial. I hope you enjoyed the basic series.
We will use 3 files here: the protected.php, after logging in; the login.php, the page to login.
Here is the login.php
<?php
session_start();
if ($_GET['login']) {
// Only load the code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['username'] == 'USERNAME'
&& $_POST['password'] == 'PASSWORD') {
// Load code below if both username
// and password submitted are correct
$_SESSION['loggedin'] = 1;
// Set session variable
header("Location: protected.php");
exit;
// Redirect to a protected page
} else echo "Wrong details";
// Otherwise, echo the error message
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="?login=1" method="post">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" />
</form>
</body>
And the protected.php page :
<?php
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['loggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: login.php");
exit;
}
?>
PROTECTED STUFF HERE (HTML/PHP)
Thank-you for reading this tutorial. I hope you enjoyed the basic series.