Over a million developers have joined DZone.

Simple Password Protection Using PHP

DZone's Guide to

Simple Password Protection Using PHP

Free Resource
Use this simple script to password protect your pages, Ideal for password protecting Administrative parts or sensitive parts of your web site.

The logic behind the script is very simple when ever your password protected page is called the script is first called it checks for the username and password if not found, presents you with a login page and when you submit info (username, password) it checks if the info is correct if correct allows you to access the protected page, else denies access. 

 To protect a particular page use the include directive to include this script in your page.Example: 




		<?php echo $HTTP_SERVER_VARS['HTTP_HOST']; ?> : Authentication Required



(Access Restricted to Authorized Personnel)

User Name
$host : Administration
You Need to log on to access this part of the site!

"; echo "Error: You are not authorized to access this part of the site! Click here to login again.

"; session_unregister("adb_password"); session_unregister("user"); exit; } $user_checked_passed = false; if(isset($HTTP_SESSION_VARS['adb_password'])) { $adb_session_password = $HTTP_SESSION_VARS['adb_password']; $adb_session_user = $HTTP_SESSION_VARS['user']; if($admin_password != $adb_session_password) login_error($HTTP_SERVER_VARS['HTTP_HOST'],$HTTP_SERVER_VARS['PHP_SELF']); else { $user_checked_passed = true; } } if($user_checked_passed == false) { if(strlen($u_name)< 2) login_error($HTTP_SERVER_VARS['HTTP_HOST'],$HTTP_SERVER_VARS['PHP_SELF']); if(isset($admin_password)) { if($admin_password == $u_password) { session_register("adb_password"); session_register("user"); $adb_password = $admin_password; $user = $u_name; } else { //password in-correct login_error($HTTP_SERVER_VARS['HTTP_HOST'],$HTTP_SERVER_VARS['PHP_SELF']); } } else { login_error($HTTP_SERVER_VARS['HTTP_HOST'],$HTTP_SERVER_VARS['PHP_SELF']); } $page_location = $HTTP_SERVER_VARS['PHP_SELF']; if(isset($HTTP_SERVER_VARS["QUERY_STRING"])) $page_location = $page_location ."?". $HTTP_SERVER_VARS["QUERY_STRING"]; header ("Location: ". $page_location); } } } ?>

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}