Easiest Way to Protect Page(s) using PHP and PHP SESSIONS

When I needed to create admin section for my first php driven website I was looking all over for a simple tutorial like this. There are tons of scripts out there for this function, but most of them use php and mySql database which was out of my league at the time. So I decided to simplify this so people in the beginning stage would benefit from it.

Create a new BLANK document in notepad called secured.php. Add the following code in the page >> Save >> Upload to your server.
Then access the file from your domainname.com/secured.php. Enter Username (admin) and Password (adminpass) and it should work :)

<?php
//always start session
session_start();

//lets look to see if form has been submitted with a field "username"
if(isset($_POST['username'])){
//you can change the username and password value here...

 if(($_POST['username'] == "admin") && ($_POST['password'] == "adminpass")){
  //if username and passwords match then create session called "secured"
  $_SESSION['secured'] = "Secured";
 }else{
// if the values don't match... show error message

  echo "Oop! Looks like the username and password is not what I'm looking for, sorry you can't continue :( <p>
  <a href='?'>Lets try that again...</a>";
 }
}
//done creating session.
 
//if there IS NO sessions called "secured"
if(!isset($_SESSION['secured'])){
//then display a simple form
//feel free to customize your form nicely :)
echo "<form method='post'>
Username: <input type='text' name='username' maxlength='10' /><br>
Password: <input type='password' name='password' maxlength='10' /><br>
<input type='submit' value='login' />
</form>";
}else{
//else if the session is created... show me the HTML page :)
?>
 

 
<html>
<head>
<title>Session Login</title>
</head>
<body>
<p>You have been successfully logged in :)... now lets add some content in this secured page.
</p>
</body>
</html>
 
 
<?php
}
//this closes the else statement... DONE!!!
?>

If you have any questions regarding this tutorial, please send me an email at evan at evanislam.com. Goodluck :)


Add New Comment
Your Name
Email Address
Homepage
Comment
Human Verification 4 2 =