PHP Tutorial : Password protect page script

Do you have some content which you do not want to show to public? There is a php script which “hides” the content, protecting it with a password and username to access a page. It can be done with MySQL database but I really want to keep things simplier and I will do without mysql, just pure php.
It will use a php session with session_start() function and an if / else sequence/condition.
Also, there will be a html form with the username and password requirements.

<?php
session_start();
$_SESSION['loggedin'] = "";
$username = "youruser";
$password = "yourpassword";
if($_SESSION['loggedin'] == "" || !isset($_SESSION['loggedin'])) {

print '<form action="" method="POST">';
print 'username : <input type="text" name="username"><br/>
       password : <input type="password" name="password"><br/>';
print "<input type='submit' name='sb' id='sb' value='login'>";
print '</form>';
}elseif($_SESSION['loggedin'] != "" || isset($_SESSION['loggedin'])) {

if(isset($_POST['sb'])) {

if($_POST['username'] == "" || $_POST['password'] == "") {

print 'fill into fields';
}else{

if($_POST['username'] == "$username" and $_POST['password'] == "$password") {

print "you're logged in";
//put more protected content here
}
}
}
}
?>
This entry was posted in Usefull PHP and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to PHP Tutorial : Password protect page script

  1. lijo says:

    hi,

    thanks for the nice site . but i am using WAMP server on my pc . when i tried to run the script i got the following error

    Parse error: parse error in C:\wamp\www\test\2.php on line 6

    please tell me whats wrong .

    thanks in advance

  2. admin says:

    thanks, problem is solved, please recopy the code and let me know!
    cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>