Well you can always try this out to help you learn.. This is quite an advanced script for a person introduced to PHP. But - Maybe you can follow it 🙂
Heres the first way to only allow a certain user to login (predefined username & password)
<?php
session_start();
function clean($data)
{
return htmlspecialchars(addslashes($data));
}
if($_SESSION['is_logged_in'] == false)
{
if((!isset($_POST['username']) || empty($_POST['username'])) || (!isset($_POST['password']) || empty($_POST['password'])))
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="Login">
</form>
<?php
}
else
{
$allowedusername = "Member"; // Allowed username to login with
$allowedpassword = "Password"; // Allowed password to login with
$username = clean($_POST['username']);
$password = clean($_POST['password']);
if($username == $allowedusername && $password == $allowedpassword)
{
$_SESSION['is_logged_in'] = true;
echo "You are now logged in.";
}
else
{
$_SESSION['is_logged_in'] = false;
echo "Invalid Login.";
}
}
}
else
{
echo "You are already logged in.";
}
?>
or you can use MySQL to keep track of multiple users without using large arrays..
<?php
session_start();
// Lets connect to mysql - You might want to read a few tutorials on how to connect and create databases.
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$mysql_members_table = "members";
function clean($data)
{
return htmlspecialchars(addslashes($data));
}
function draw_form()
{
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?action=login">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="Login">
</form>
<?php
}
function login()
{
if((!isset($_POST['username']) || empty($_POST['username'])) || (!isset($_POST['password']) || empty($_POST['password'])))
{
draw_form();
}
else
{
$username = clean($_POST['username']);
$password = clean($_POST['password']); // or you can use $password = md5($_POST['password']) if you plan on using encryption.
$query = mysql_query("SELECT * FROM $mysql_members_table WHERE username='".$username."' AND password = '".$password."'") or die(mysql_error());
if(mysql_num_rows($query) == 1)
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
echo "You are now logged in.";
}
else
{
session_destroy();
echo "Invalid username OR password.";
}
}
}
function logout()
{
if(isset($_SESSION['username']) && isset($_SESSION['password']))
{
session_destroy();
echo "You are now logged out.";
}
else
{
echo "You are not logged in.";
}
}
switch(clean($_GET['action']))
{
case "login":
login();
break;
case "logout":
logout();
break;
default:
login();
break;
}
?>
Have fun and good luck 🙂