Solved

secure PHP password protection

Posted on 2014-09-16
17
197 Views
Last Modified: 2014-09-21
Can someone please review this code and help me figure out why its breaking? I am getting the following error and the code is not working:

Warning: Cannot modify header information - headers already sent by (output started at /home/drgryan/elizabethustore.com/password_protect_elizabeth.php:1) in /home/drgryan/elizabethustore.com/password_protect_elizabeth.php on line 98

 <?php
# Simple password protection
#
# (c) http://www.phpbuddy.com
# Author: Ranjit Kumar
# Feel free to use this script but keep this message intact!
# 
# To protect a page include this file in your PHP pages!



$admin_user_name = "test"; 
$admin_password = "tester";
//you can change the username and password by changing the above two strings 

if (!isset($_SESSION['user'])) 
{
	
	if(isset($_POST['u_name'])) 
		$u_name = $_POST['u_name'];
	
	if(isset($_POST['u_password'])) 
		$u_password = $_POST['u_password'];
	
	if(!isset($u_name)) 
	{
		?>
        
		<HTML>
		
		
		
		<BODY bgcolor=#ffffff>
					  (Access Restricted to Authorized Personnel)  			  
		
		
		
		<?php
		$form_to = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]";
		
//		if(isset($_SERVER["QUERY_STRING"]))
//		$form_to = $form_to ."?". $_SERVER["QUERY_STRING"];
		
		?>
		<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				 		 User Name 		 <input type=text name=u_name size=20> 		 		 Password 		 <input type=password name=u_password size=20> 		 		 
		<input type=submit value=Login></form>
		
		
		</BODY>
		</HTML>
		
		<?php
		exit;
	}
	else 
	{
		
		function login_error() 
		{
			echo "<HTML>
			
			<BODY bgcolor=#ffffff>
							  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.
			
			
			</BODY>
			</HTML>";
			session_unregister("adb_password");
			session_unregister("user");
			exit;
		}
		
		
		if ($u_name == $admin_user_name)
		{
			if ($u_pass = $admin_password)
			{
				$_SESSION["user"] = $u_name;
			}
		}
		else
			login_error();
			
		
		
				
			$page_location = $_SERVER['PHP_SELF'];
			if(isset($_SERVER["QUERY_STRING"]))
				$page_location = $page_location ."?". $_SERVER["QUERY_STRING"];
			
			header ("Location: ". $page_location);
	}
}
?>

Open in new window

0
Comment
Question by:johnsonrobbins
  • 7
  • 7
  • 2
  • +1
17 Comments
 
LVL 11

Assisted Solution

by:Radek Baranowski
Radek Baranowski earned 250 total points
ID: 40325216
it's a warning,
and probably you are trying to set header more than once, hence the message about headers already sent
0
 

Author Comment

by:johnsonrobbins
ID: 40325227
ok? how do I fix the code to make the logic work.. right now the user is able to go right through the password page
0
 
LVL 11

Expert Comment

by:Radek Baranowski
ID: 40325252
what do you want to achieve with

$page_location = $_SERVER['PHP_SELF'];
			if(isset($_SERVER["QUERY_STRING"]))
				$page_location = $page_location ."?". $_SERVER["QUERY_STRING"];
			
			header ("Location: ". $page_location);

Open in new window

0
 

Author Comment

by:johnsonrobbins
ID: 40325291
I am able to add this in the header of a page

<?php
include "password_protect_elizabeth.php";
?>

when the user hits a page with that in the header it automatically loads the provided code prompting user to enter a password. while I am not an expert in php, my guess is $page_location = $_SERVER['PHP_SELF']; is saying that if the correct password is entered then return to the page you tried to get to. (my best guess, its just code i found on the internet)
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325354
This warning is so common that E-E has an article about it!  See HTTP Headers Must Come First, Period
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/A_11271-Understanding-Client-Server-Protocols-and-Web-Applications.html

To the more practical design pattern of client/server authentication in PHP, we also have an article about that!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

I would be highly suspicions of any code that contained something like <BODY bgcolor=#ffffff>.  That almost guarantees that the author is not following modern programming techniques.  It might be better to start with some stronger learning resources, especially if you're new to PHP.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 

Author Comment

by:johnsonrobbins
ID: 40325368
While I appreciate your feedback Ray, your comments are not useful. This code has worked for me in the past and I would imagine someone who has some PHP background could pick out the issue and debug it pretty quick. Thanks for the resources though.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325438
Well, for starters, you might try removing the blank before the start-PHP tag.

Sorry if you think the comments are not useful.  I think if you read the articles you will have a better understanding of what you're trying to achieve here!
0
 

Author Comment

by:johnsonrobbins
ID: 40325455
sorry, my comment may have come across as more abrasive than necessary. I really am just looking for direct help not education. I wish I had more time to learn PHP but in the meantime I am just looking for an exact solution. I'm sure the articles are brilliant!
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325461
Did you try removing the blank before the start-PHP tag?
0
 

Author Comment

by:johnsonrobbins
ID: 40325513
yes, seems to be validating now only on the user name not password and it just returns to the login page, does not proceed to the targeted page. If the user name is incorrect it is displaying (You Need to log on to access this part of the site! Error: You are not authorized to access this part of the site! Click here to login again.) You can ping the site with the following url

http://www.elizabethustore.com/elizabethadmin.php

test/tester
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325521
I don't doubt that the code worked for you once some time ago, but times are changing, especially for PHP, which is growing up as a programming language.  See the warning on this page.  This script is just too old to still be considered workable.  It's time to refactor.
http://www.php.net/manual/en/function.session-unregister.php
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 40325531
Maybe you need to wrap those lines in brackets:

if (isset($_SERVER["QUERY_STRING"])){
            $page_location = $page_location . "?" . $_SERVER["QUERY_STRING"];
            header("Location: " . $page_location);
        }

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325536
You may also want to add session_start().  Not surprisingly this is another one of those frequent questions with an article to explain it!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 40325568
I think this may get you closer to the right idea.  At line 46, that's where you might put your header() to redirect the client browser.  Or you could just include() the appropriate script/document.

See: http://iconoun.com/demo/temp_johnsonrobbins.php
<?php // demo/temp_johnsonrobbins.php
error_reporting(E_ALL);

// ALWAYS START THE SESSION ON EVERY PAGE
session_start();

// CHANGE THESE VALUES TO CHANGE USERNAME AND PASSWORD
$admin_user_name = "test";
$admin_password  = "tester";

// PESSIMISTIC ASSUMPTION
$auth  = FALSE;
$error = 'ERROR IN LOGIN CREDENTIALS';

// IF THE SESSION AUTHORIZES THE CLIENT
if (!empty($_SESSION['user']))
{
    $auth  = TRUE;
    $error = NULL;
}

// IF THERE IS A POST-METHOD REQUEST
if (!empty($_POST))
{
    $u_name = !empty($_POST['u_name']) ? $_POST['u_name'] : NULL;
    $u_pass = !empty($_POST['u_pass']) ? $_POST['u_pass'] : NULL;
    if ($u_name == $admin_user_name)
    {
        if ($u_pass == $admin_password)
        {
            $auth = TRUE;
            $_SESSION['user'] = $u_name;
            $error = NULL;
        }
    }
}
// IF THERE IS NO POST-METHOD REQUEST
else
{
    $error = NULL;
}

// IF AUTHORIZATION
if ($auth)
{
    echo "YOU ARE AUTHORIZED, " . $_SESSION['user'];
}
// IF NOT AUTHORIZED, CREATE THE FORM
else
{
    $htm = <<<EOD
$error<br>
YOU ARE NOT AUTHORIZED YET
<form method="post">
User Name <input name="u_name" /><br>
Pass Word <input name="u_pass" /><br>
<input type="submit" value="Login" />
</form>
EOD;

    echo $htm;
}

Open in new window

0
 

Accepted Solution

by:
johnsonrobbins earned 0 total points
ID: 40325574
I was able to get this code working.. thanks. I just copied it from another site Im using it in.. have no idea what was wrong with the previous version.. thanks for your help.

<?php
# Simple password protection
#
# (c) http://www.phpbuddy.com
# Author: Ranjit Kumar
# Feel free to use this script but keep this message intact!
#
# To protect a page include this file in your PHP pages!

session_start();

$admin_user_name = "test";
$admin_password = "tester";
//you can change the username and password by changing the above two strings

if (!isset($_SESSION['user']))
{
      
      if(isset($_POST['u_name']))
            $u_name = $_POST['u_name'];
      
      if(isset($_POST['u_password']))
            $u_password = $_POST['u_password'];
      
      if(!isset($u_name))
      {
            ?>
       
            <HTML>
            
            
            
            <BODY bgcolor=#ffffff>
                                (Access Restricted to Authorized Personnel)                     
            
            
            
            <?php
            $form_to = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]";
            
//            if(isset($_SERVER["QUERY_STRING"]))
//            $form_to = $form_to ."?". $_SERVER["QUERY_STRING"];
            
            ?>
            <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                                      User Name              <input type=text name=u_name size=20>                           Password              <input type=password name=u_password size=20>                          
            <input type=submit value=Login></form>
            
            
            </BODY>
            </HTML>
            
            <?php
            exit;
      }
      else
      {
            
            function login_error()
            {
                  echo "<HTML>
                  
                  <BODY bgcolor=#ffffff>
                                            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.
                  
                  
                  </BODY>
                  </HTML>";
                  session_unregister("adb_password");
                  session_unregister("user");
                  exit;
            }
            
            
            if ($u_name == $admin_user_name)
            {
                  if ($u_pass = $admin_password)
                  {
                        $_SESSION["user"] = $u_name;
                  }
            }
            else
                  login_error();
                  
            
            
                        
                  $page_location = $_SERVER['PHP_SELF'];
                  if(isset($_SERVER["QUERY_STRING"]))
                        $page_location = $page_location ."?". $_SERVER["QUERY_STRING"];
                  
                  header ("Location: ". $page_location);
      }
}
?>
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40325650
It worked because the new copy of the script (1) does not have the blank character before the <?php tag, and (2) the new copy of the script includes session_start().  It's going to continue to work until the logic takes you to the session_unregister() function call, then you'll get a fatal error.  In respect of your time, you might want to get a professional programmer involved to help with this.  It will not cost you very much money and it will get you a script that works with modern PHP installations in a dependable way.
0
 

Author Closing Comment

by:johnsonrobbins
ID: 40335069
it worked
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

This is a PowerShell web interface I use to manage some task as a network administrator. Clicking an action button on the left frame will display a form in the middle frame to input some data in textboxes, process this data in PowerShell and display…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now