Worth2Read
Home

Forum

PHP Tutorials
Blogs
Children
Article Directory

Contact Us

Disclaimer
Reliable $1 Web Hosting by 3iX
 

If you have any doubts with your PHP code please discuss it in the PHP Forum

Password Protect a Webpage using PHP | My SQL

Sometimes some pages need to be password protected. For example some websites have special privileages for members --- access to certain pages may be reserved only for members.

This can be done in two ways.

  • Storing username and password in a database

  • Storing username and password as arrays.

In this tutorial I am explaining how this can be done using MySql database as backend.

The situation can be summarized as follows. There are 2 webpages, say page1 and page2 that need to be password protected. Login information is stored in the table tb_signup.

The code for page1.php is as follows.

<?php
session_start();
if ($_SESSION['user_logged_in']=="true")
{
?>

<html>
<head>
<title> Page 1</title>
</head>
<body>
<h1>Page1</h1>
<p>Hello <strong><?php echo $_SESSION['valid_user']; ?></strong>,</p>
<p>One secret here. It is available only for members like you </p>
<a href="exit.php">Logout</a>

<?php
}
else
{
include("login.php");
$back_url='http://www.worth2read.org/test/pag1.php.php';//This is the url of this page
login_form($back_url);
}
?>

</body>
</html>

Explanation of the above code:

Here the session is started and checks whether the user has already logged in.. If the user has logged in the content of the page will be displayed. Otherwise login.php is called to login.

login.php

<?php
session_start();
function login_form($back_url)
{
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>

<h1>Login Here</h1>
<form name="loginform" id="loginform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>Username
<input name="username" type="text" id="username" size="30" maxlength="30" />
</p>
<p> Password
<input name="password" type="password" id="password" size="30" maxlength="30" />
</p>
<p>
<input type="submit" name="submit" value="Submit" />
</p>
</form>

<?php

if(isset($_POST['submit'])){
$userid = $_POST["username"];
$password = $_POST["password"];
$db = mysql_connect ( "localhost" , "user_name" , "password" )or die('Cannot connect to the database because: ' . mysql_error());
mysql_select_db ("database_name ");
if($rec=mysql_fetch_array(mysql_query("SELECT * FROM tb_signup WHERE userid='$userid' AND password = '$password'"))){
if(($rec['userid']==$userid)&&($rec['password']==$password)){

$_SESSION['cust_logged_in']='true';

$_SESSION['valid_user']=$userid;

print "<script>";
print " self.location='$back_url';";
print "</script>";

}
}
}
}
?>

In a similar way we can include login.php in page2 also. We have to add username and password to the table tb_signup.

Copyright © 2008 www.worth2read.org. All rights Reserved. Use of this Site is subject to our Privacy Statement
Untitled Document
PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide
Programming PHP