Solved

secure PHP password protection

Posted on 2014-09-16
17
215 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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 110

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 110

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
 
LVL 110

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 110

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 110

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 110

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 110

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

737 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