Warning: Table './db79366_designmess/sessions' is marked as crashed and should be repaired query: SELECT u.*, s.* FROM users u INNER JOIN sessions s ON u.uid = s.uid WHERE s.sid = '64142622aa14c2a2109caa38d8eb5158' in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc on line 128

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc:128) in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/bootstrap.inc on line 1037

Warning: Cannot modify header information - headers already sent by (output started at /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc:128) in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/bootstrap.inc on line 636

Warning: Cannot modify header information - headers already sent by (output started at /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc:128) in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/bootstrap.inc on line 637

Warning: Cannot modify header information - headers already sent by (output started at /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc:128) in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/bootstrap.inc on line 638

Warning: Cannot modify header information - headers already sent by (output started at /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/database.mysqli.inc:128) in /nfs/c05/h04/mnt/79366/domains/designmess.com/html/includes/bootstrap.inc on line 639
Protecting your files with a PHP Login Script | [field_tutorial_category-term] | Designmess

Protecting your files with a PHP Login Script

Submitted by on

Getting Started

First, lets create the files we need. The password protect file itself is only one file, but we'll be styling the page as well. Create these files:

  • protect.php - Protect Script
  • index.php - File you want to protect
  • style.css - Stylesheet

The PHP

Now lets write the important part of the script. The PHP will make the script function and define the necessary credentials needed to log in.

In your protect.php file, place this script at the top:

  1. <?php
  2. $LOGIN_INFORMATION = array(
  3. 'demo' => 'demo', // Format is Username, then Password
  4. 'username' => 'password' // Each line is new user
  5. );
  6.  
  7. // CHANGE THIS- User will be redirected to this page after logout
  8. define('LOGOUT_URL', 'index.php');
  9.  
  10. // Time out after _ minutes of inactivity. Set to 0 to not timeout
  11. define('TIMEOUT_MINUTES', 10);
  12.  
  13. define('TIMEOUT_CHECK_ACTIVITY', true);
  14.  
  15. // Timeout in seconds
  16. $timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);
  17.  
  18. // Logout?
  19. if(isset($_GET['logout'])) {
  20. setcookie("verify", '', $timeout, '/'); // clear password;
  21. header('Location: ' . LOGOUT_URL);
  22. exit();
  23. }
  24.  
  25. if(!function_exists('showLoginPasswordProtect')) {
  26.  
  27. // Show login form
  28. function showLoginPasswordProtect($error_msg) {
  29. ?>

Basically, the script above defines user(s) who can login. If you want to add multiple users, just copy the line in the top where there are users and define some new usernames and passwords. Then there is a cookie timeout that you can change.
Great, now that we have the basic PHP all set up, lets write the HTML.

The HTML

Lets give our login form some style. Wrap your HTML around the form element, which is all you actually need (but its always nice if it looks good).

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  4. <title>Password Demo</title>
  5. <link rel="stylesheet" type="text/css" href="style.css" media="screen" />
  6. </head>
  7.  
  8. <div id="header">
  9. <div id="message">
  10. </div>
  11. </div><!--header-->
  12.  
  13. <div id="wrapper">
  14. <div id="page">
  15. <form method="post">
  16. <?php if ($error_msg): ?><div id="error"><?php echo $error_msg; ?></div><?php endif; ?>
  17. <label>Username</label><input type="input" name="access_login" /><br />
  18. <label>Password</label><input type="password" name="access_password" /><br />
  19. <input type="submit" name="Submit" value="Login" class="submit" />
  20. </form>
  21. </div><!--page-->
  22. </div><!--wrapper-->
  23.  
  24. </body>
  25. </html>

We aren't done with the basic markup yet. There's still a bit of PHP we need to add.

The Final PHP

We need to close our PHP functions, so let's place this code right after the HTML.

  1. <?php
  2. // stop at this point
  3. die();
  4. }
  5. }
  6.  
  7. // user provided password
  8. if (isset($_POST['access_password'])) {
  9.  
  10. $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  11. $pass = $_POST['access_password'];
  12. if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  13. || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) )
  14. ) {
  15. showLoginPasswordProtect("Incorrect password.");
  16. }
  17. else {
  18. // set cookie if password was validated
  19. setcookie("verify", md5($login.'%'.$pass), $timeout, '/');
  20.  
  21. // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
  22. // So need to clear password protector variables
  23. unset($_POST['access_login']);
  24. unset($_POST['access_password']);
  25. unset($_POST['Submit']);
  26. }
  27.  
  28. }
  29.  
  30. else {
  31.  
  32. // check if password cookie is set
  33. if (!isset($_COOKIE['verify'])) {
  34. showLoginPasswordProtect("");
  35. }
  36.  
  37. // check if cookie is good
  38. $found = false;
  39. foreach($LOGIN_INFORMATION as $key=>$val) {
  40. $lp = (USE_USERNAME ? $key : '') .'%'.$val;
  41. if ($_COOKIE['verify'] == md5($lp)) {
  42. $found = true;
  43. // prolong timeout
  44. if (TIMEOUT_CHECK_ACTIVITY) {
  45. setcookie("verify", md5($lp), $timeout, '/');
  46. }
  47. break;
  48. }
  49. }
  50. if (!$found) {
  51. showLoginPasswordProtect("");
  52. }
  53.  
  54. }
  55.  
  56. ?>

So, your markup for the protect.php page should go like this:

  • PHP (Defining timeout and user credentials)
  • The HTML
  • Closing PHP

You may also have noticed that we link to the stylesheet (style.css) in the HTML. But before we start styling the CSS, lets make the images we need.

The Images

For the purposes of this page, I whipped up some simple images (with the submit button from our other tutorial: Creating Awesome Buttons with CSS and Image Sprites.

Here are the images I created:

Great! Now that we have the images all set, lets move on to the CSS.

The CSS

The stylesheet I wrote is pretty basic. Just copy the code below (or write your own CSS) and put it in style.css. If you have a question about any of the styles, feel free to ask a question in the comments.

  1. * {
  2. margin: 0;
  3. padding: 0;
  4. }
  5.  
  6. body {
  7. background: transparent url(images/body-bg.gif) repeat top left;
  8. font-family: Helvetica, Arial, sans-serif;
  9. font-size: 14px;
  10. color: #FFFFFF;
  11. }
  12.  
  13. #header {
  14. background: #010101 url(images/header-bg.jpg) no-repeat top center;
  15. width: 100%;
  16. height: 150px;
  17. position: relative;
  18. clear: both;
  19. border-bottom: 1px solid #000000;
  20. }
  21.  
  22. #header-wrapper {
  23. width: 960px;
  24. margin: 0 auto;
  25. }
  26.  
  27. #message {
  28. background: transparent url(images/message.png) no-repeat top left;
  29. width: 540px;
  30. height: 80px;
  31. display: block;
  32. margin: 0 auto;
  33. position: relative;
  34. top: 35px;
  35. }
  36.  
  37. #logo {
  38. background: transparent url(images/logo.png) no-repeat top left;
  39. width: 280px;
  40. height: 80px;
  41. display: block;
  42. margin: 0 auto;
  43. position: relative;
  44. top: 35px;
  45. }
  46.  
  47. #wrapper {
  48. border-top: 1px solid #444444;
  49. position: relative;
  50. width: 100%;
  51. clear: both;
  52. }
  53.  
  54. #page {
  55. width: 600px;
  56. margin: 20px auto;
  57. text-align: center;
  58. }
  59.  
  60. input {
  61. -moz-border-radius: 4px;
  62. -webkit-border-radius: 4px;
  63. border-radius: 4px;
  64. -khtml-border-radius: 4px;
  65. background: #FFFFFF;
  66. border: none;
  67. margin: 5px 0;
  68. padding: 4px 6px;
  69. box-shadow: 0 2px 20px #141414;
  70. -moz-box-shadow: 0 2px 20px #141414;
  71. -webkit-box-shadow: 0 2px 20px #141414;
  72. font-size: 18px;
  73. }
  74.  
  75. label {
  76. margin-right: 10px;
  77. font-size: 18px;
  78. }
  79.  
  80. .submit {
  81. display: inline-block;
  82. background: transparent url(images/btn-green.png) repeat-x 0 0;
  83. border: 1px solid #1C3600;
  84. -moz-border-radius: 20px;
  85. -webkit-border-radius: 20px;
  86. border-radius: 20px;
  87. -khtml-border-radius: 20px;
  88. padding: 4px 8px;
  89. margin: 6px 0;
  90. color: #213E01;
  91. text-decoration: none;
  92. font-weight: bold;
  93. font-size: 16px;
  94. text-shadow: 0 -1px #6FD700;
  95. line-height: 18px;
  96. cursor: pointer;
  97. box-shadow: 0 1px 12px #141414;
  98. -moz-box-shadow: 0 1px 12px #141414;
  99. -webkit-box-shadow: 0 1px 12px #141414;
  100. }
  101.  
  102. #error {
  103. background: #FFC1C1;
  104. border: 1px solid #B93B3B;
  105. color: #B93B3B;
  106. padding: 4px;
  107. width: 100%;
  108. }

Awesome! That takes care of the basic functionality of our login script.

Protecting a File

Let's say you want to protect your index.php file. All you need to do is include the protect.php script in the top of any document you want to protect.

Like so:

  1. <?php include("protect.php"); // Just include this in any file you want to protect ?>

Questions? Concerns? Feedback?

I highly recommend checking out the demo and downloading the source files before asking questions. After that, I'd be glad to help you. Just post a comment below!

Internet Nerd, Design Freak, oh and Designmess Admin.

About Sean GengMember Since 08/03/2009

Web Designer, Web Developer

My name is Sean Geng. I'm a Freelance Web Designer, Graphic Designer, Motion Effects Artist, and Webmaster. I like to push the boundaries. I love creating unique, clean, usable design for the web and other digital sources.

CommentsAdd your comment

very very very useful.thanks Works perfect

February 24, 2010 - 5:31pm

Great script, works perfect. But how to implement the logout feature? There's the line "define('LOGOUT_URL', 'http://designmess.com');" in protect.php but there's no action or button opting to logout.

March 29, 2010 - 3:23am

I'm new to php and trying to learn it quick because I'm designing a page for a client who wants users to be able to enter a password to access a personalized schedule. Would this script be able to be modified to direct a user to a certain page based on their username?

April 3, 2010 - 5:10pm

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <h3> <h4> <i> <b> <p> <a> <br /> <img> <em> <strong> <blockquote> <cite> <code> <ul> <ol> <li> <div class="info-block-left"> <div class="info-block-right"> <div class="quote-left"> <div class="quote-right"> <div class="notice"> <table> <thead> <tbody> <tr class="odd"> <tr class="even"> <tr> <td> <th>
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <actionscript-code>, <actionscript3-code>, <apache-code>, <asp-code>, <css-code>, <html-code>, <javascript-code>, <mysql-code>, <php-code>, <python-code>, <ruby-code>, <sql-code>, <xml-code>. The supported tag styles are: <foo>, [foo].
  • Images can be added to this post.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.
  • Links to HTML content with 'rel="lightframe"' in the <a> tag will appear in a Lightbox when clicked on.
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.
  • You may insert videos with [video:URL]

More information about formatting options

Other stories you might like

Sorry if its gonna be slow content wise for a week or so. Working on a free wordpress theme. Consider writing for us?