Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 232
  • Last Modified:

secure PHP password protection

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
johnsonrobbins
Asked:
johnsonrobbins
  • 7
  • 7
  • 2
  • +1
3 Solutions
 
Radek BaranowskiFull-stack Java DeveloperCommented:
it's a warning,
and probably you are trying to set header more than once, hence the message about headers already sent
0
 
johnsonrobbinsAuthor Commented:
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
 
Radek BaranowskiFull-stack Java DeveloperCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
johnsonrobbinsAuthor Commented:
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
 
Ray PaseurCommented:
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
 
johnsonrobbinsAuthor Commented:
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
 
Ray PaseurCommented:
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
 
johnsonrobbinsAuthor Commented:
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
 
Ray PaseurCommented:
Did you try removing the blank before the start-PHP tag?
0
 
johnsonrobbinsAuthor Commented:
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
 
Ray PaseurCommented:
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
 
Lukasz ChmielewskiCommented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
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
 
johnsonrobbinsAuthor Commented:
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
 
Ray PaseurCommented:
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
 
johnsonrobbinsAuthor Commented:
it worked
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 7
  • 7
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now