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 } } } } ?>

Tags: , , , , , , , , , , , , , ,

2 Comments »

  1. lijo Said,

    February 6, 2009 @ 5:48 am

    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 Said,

    February 6, 2009 @ 6:15 am

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

RSS feed for comments on this post · TrackBack URI

Leave a Comment