Solved

Simple login form with php

Posted on 2013-01-17
15
604 Views
Last Modified: 2013-01-18
Hello Experts.

I have a simple page that works as back-office, that shows a table from the DB within an html table, and also has a form that adds info to the table.

I need to have this page secured with a log-in, so only one defined user, the admin, would have acess to. No need for other users.

Here is the code I am working with:

<?php

session_start();

// ***************************************** //
// **********	DECLARE VARIABLES  ********** //
// ***************************************** //

$username = 'username';
$password = 'password';

$random1 = 'secret_key1';
$random2 = 'secret_key2';

$hash = md5($random1.$password.$random2); 

$self = $_SERVER['REQUEST_URI'];


// ************************************ //
// **********	USER LOGOUT  ********** //
// ************************************ //

if(isset($_GET['logout']))
{
	unset($_SESSION['login']);
}


// ******************************************* //
// **********	USER IS LOGGED IN	********** //
// ******************************************* //

if (isset($_SESSION['login']) && $_SESSION['login'] == $hash) {

	?>
			
		<?php include 'backoffice.php'; ?>
		<a href="?logout=true">Logout?</a>
			
	<?php
}


// *********************************************** //
// **********	FORM HAS BEEN SUBMITTED	********** //
// *********************************************** //

else if (isset($_POST['submit'])) {

	if ($_POST['username'] == $username && $_POST['password'] == $password){
	
		//IF USERNAME AND PASSWORD ARE CORRECT SET THE LOG-IN SESSION
		$_SESSION["login"] = $hash;
		header("Location: $_SERVER[PHP_SELF]");
		
	} else {
		
		// DISPLAY FORM WITH ERROR
		display_login_form();
		echo '<p>Username or password is invalid</p>';
		
	}
}	
	
	
// *********************************************** //
// **********	SHOW THE LOG-IN FORM	********** //
// *********************************************** //

else { 

	display_login_form();

}


function display_login_form(){ ?>

	<form action="<?php $self = $_SERVER['REQUEST_URI']; echo $self; ?>" method='post'>
	<label for="username">username</label>
	<input type="text" name="username" id="username">
	<label for="password">password</label>
	<input type="password" name="password" id="password">
	<input type="submit" name="submit" value="submit">
	</form>	

<?php } ?>

Open in new window


ok, in the part "<?php include 'backoffice.php'; ?>" ( line 38 ), I am including the php page with the content of the backoffice, but there is no security here, since I can go to that page individually and dont need any log-in.

I have tried to include the all the code from the backoffice in that same line, works, but it's a mess, and I thought that should be a better way to do it, better ask to who knows.

Also, is this code "ok"? Don't need ultra security, but dont want it to be easy too.

Thanks for the help guys.


Cheers
0
Comment
Question by:joao_c
  • 5
  • 5
  • 2
  • +2
15 Comments
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 38788858
I have some code I wrote (for another question on EE) and it helped that person.  Perhaps it will help you too.  This is a very simple set of scripts that illustrate how to detect if someone is logged in, etc.  It doesn't include actually asking the user for credentials.  However, since you are seeing a page you aren't supposed to without a login, these script examples might be just what you need.  (Of course, you'll have to decide.)

login.php
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>Logout</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="Author" content="hmccurdy" />
</head>
<body>
<?php
  if ( isset ( $_SESSION [ 'authenticated' ] ) && ( $_SESSION [ 'authenticated' ] == TRUE ))
    echo '<h3>You were already logged in.</h3>';
  else
    echo '<h3>Logging you in.</h3>';

  $_SESSION [ 'authenticated' ] = TRUE;
  $_SESSION [ 'name' ] = "Edward Bear";
?>

  <a href='login.php'>Login</a><br />
  <a href='status.php'>Status</a><br />
  <a href='bounce.php'>Bounce</a><br />
  <a href='logout.php'>Logout</a><br />
</body>
</html>

Open in new window


logout.php
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<?php session_destroy(); ?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>Logout</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="Author" content="hmccurdy" />
</head>
<body>
  <h3>You are logged out.</h3>

  <a href='login.php'>Login</a><br />
  <a href='status.php'>Status</a><br />
  <a href='bounce.php'>Bounce</a><br />
  <a href='logout.php'>Logout</a><br />
</body>
</html>

Open in new window


status.php
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>Logout</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="Author" content="hmccurdy" />
</head>
<body>
  <h3>Contents of $_SESSION</h3>

<?php
  if ( isset ( $_SESSION ))
  {
    var_dump ( $_SESSION );
    echo "<br />\n";
  }
  else
    echo "$_SESSION not set<br />\n";

?>

  <a href='login.php'>Login</a><br />
  <a href='status.php'>Status</a><br />
  <a href='bounce.php'>Bounce</a><br />
  <a href='logout.php'>Logout</a><br />
</body>
</html>

Open in new window


bounce.php   (Illustrates how to eject someone who tries to load the page.)
<?php
session_start();

if ( ! ( isset ( $_SESSION [ 'authenticated' ] ) && ( $_SESSION [ 'authenticated' ] == TRUE )))
  header ( 'location: login.php' );

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
   "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>Logout</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="Author" content="hmccurdy" />
</head>
<body>
  <h3>You are in the secure area</h3>

  <a href='login.php'>Login</a><br />
  <a href='status.php'>Status</a><br />
  <a href='bounce.php'>Bounce</a><br />
  <a href='logout.php'>Logout</a><br />
</body>
</html>

Open in new window

0
 

Author Comment

by:joao_c
ID: 38789042
Thanks for the reply @hmccurdy :)

I was looking for something more simple (not so many pages). Dont need UI log-in. Just when you go to the page display a field to enter the password and that's it.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 38789128
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 38789184
Login is only one page.  The other pages are examples.

However, it sounds like you want something where a page loads that asks for a password.  If the password is correct, it loads another page.  Does that sound correct?

I'd approach this much like I'd approach any form.  PHP script generates a form that asks for user-name/password.  Form submitted.  Form verified.  If verifcation fails, script simply generates the first page again (asking for user-name/password).  If the verification passes, script generates the administrator's page.  If properly coded, the script would never generate the admin. page unless the user-name/password verifies.  (The key is that the page doesn't exist except when the PHP script generates the page.)

The next question has to do with the level of security.  For instance, you might want the script to refuse to do much of anything if there are 3 failed login attempts in a row.  But that's a different problem.

Does the above idea make sense to you?

I could write something, fairly quickly, as an example.  However, if Cd&'s approach works for you, I'm not going to duplicate the work.
0
 

Author Comment

by:joao_c
ID: 38789216
@hmccurdy, for example, when I go to backoffice.php I want it to ask for password, no need for extra files. Just the same page with the content, has that log-in built in, no need for log-out. Of course if they close the browser the session stops.

Could you help me out?

@COBOLdinosaur, too complicated for me, sorry :S, but nice looking page :D
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 38789454
I think I can throw something together for you.
0
 

Author Comment

by:joao_c
ID: 38789470
Thank you :)
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 13

Accepted Solution

by:
Hugh McCurdy earned 250 total points
ID: 38789856
It might not be as simple as you'd like for a couple reasons.
1. I put it on my website for testing which means it has code for my website (my banner, my picture).  The extra code can be stripped out.
2. I used two files, one is included in the other file because the second page can be included in one of two places in the file.

A working example is at http://hugh.tekcities.com/hugh/program/web/phpLoginSimple.php

The source code is there but I'll also paste it here.  (As I said, it can be simplified but I'm running out of time today to work on this.)

Here is the main file.
<?php error_reporting ( E_ALL );?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <link rel='stylesheet' type='text/css' href='/hugh/hugh.css'/>
  <title>Hugh McCurdy's Personal Web Site &#124; Simple Form Example using PHP</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta user="Author" content="Hugh McCurdy" />
</head>
<body>


  <div id='container'>

    <!-- Header. -->

    <header id='logo'>
      <img class='logo' id='photo' src='/hugh/hugh200.jpg' alt='Photograph of Hugh McCurdy'/>
      <h1>Hugh McCurdy's Personal Website</h1>
      <h1>Simple Login Example using PHP</h1>
    </header>

<?php include ( "../../include/topnav.html" ); ?>



    <!-- Center -->

    <div id='left_center_right'>

<?php


if ( isset ( $_POST [ 'user' ] ))
{
  $clean = array();

  $clean [ 'user' ]    = trim ( filter_input ( INPUT_POST, 'user', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ));
  $clean [ 'pass' ]    = trim ( filter_input ( INPUT_POST, 'pass', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW ));


  if (( $clean [ 'user' ] == 'admin' ) && ( $clean [ 'pass' ] == 'xxxx' ))
  {
   
    echo "<h2>Congratulations</h2>", PHP_EOL;
    echo "<p>You have authenticated yourself</p>", PHP_EOL;

  }
  else
  {
    require ( "require/phpLoginSimple.php" );
  }
}
else
  require ( "require/phpLoginSimple.php" );

?>

    <h2>Source Code</h2>
<?php require_once ( "lib/ShowFile.php" ); ?>
      <p>
	<b>phpLoginSimple.php:</b>
      </p>
<?php showFile ( "phpLoginSimple.php", "code_wide", "phpLoginSimple", 25, 80 ); ?>

      <p>
	<b>require/phpLoginSimple.php:</b>
      </p>
<?php showFile ( "require/phpLoginSimple.php", "code_wide", "require/phpLoginSimple", 25, 80 ); ?>


    </div>



<?php 
include ( "../../include/footer.html" );
include ( "../../include/validator.html" );
?>

  </div> <!-- container -->

</body>
</html>

Open in new window


Here is the included file

    <h1>Very Simple Login Script</h1>

    <p>
      I wrote this script in response to a request for help on
      <a href='http://www.experts-exchange.com' class='link'>Experts Exchange.</a>
    </p>

    <p>
      The script asks the user for a user name and a password.
      The requester only has one authorized user, the administrator.
      He didn't tell me how he meant to authenticate the password
      so I've simply used a hard coded password for purposes of this example.
    </p>

    <form action='phpLoginSimple.php' method='post' class='center'>
<?php
if ( isset ( $clean ))
{
  echo "<fieldset>" . PHP_EOL;
  echo "<legend>Please fix errors</legend>" . PHP_EOL;
  echo "<ul class='error'>" . PHP_EOL;

  echo "<li>User ID or Password is incorrect</li>" . PHP_EOL;

  echo "<li>Please login with correct credentials</li>" . PHP_EOL;

  echo "</ul>" . PHP_EOL;
  echo "</fieldset>" . PHP_EOL;
}
else
{
  $clean = array();

  $clean [ 'user' ]   = '';
  $clean [ 'pass' ]   = '';
}

?>

      <fieldset>
        <legend>Please Login</legend>
	  <ul>

<!-- I would normally set required='required' but I want to demonstrate PHP handling empty fields -->

	    <li>
	      <label for='user' class='required'>Name</label>
	      <input name='user' id='user' class='required' size='30' maxlength='60' autofocus='autofocus' 
	      value='<?php echo $clean [ 'user' ]?>'/>
	    </li>

	    <li>
	      <label for='pass' class='required'>pass</label>
	      <input name='pass' id='pass' class='required' size='30' maxlength='60'
	      value='<?php echo $clean [ 'pass' ]?>'/>
	    </li>

	</ul>
      </fieldset>

      <fieldset>
	<legend>Submit</legend>
	<input type='reset' value='Reset Form' />
	<input type='submit' value='Submit Form' />

      </fieldset>

    </form>

Open in new window


The w3 validator isn't working right now so I didn't validate the code.  It does run, though.  Hope it is what you want.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
ID: 38789914
All PHP client authentication scripts follow the same design pattern.  You can learn all about it here:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

If you're only going to have one administrator, you can probably dispense with the registration part.
0
 
LVL 5

Assisted Solution

by:Neil_Bradley
Neil_Bradley earned 150 total points
ID: 38790018
Just a suggestion but if you are looking for something very simple why not use the htaccess file to enable directory protection?
http://davidwalsh.name/password-protect-directory-using-htaccess

Cheers,
N
0
 

Author Comment

by:joao_c
ID: 38790278
Thank you so much @hmccurdy for taking the time to build that, I will have in depth look at it tomorrow and reply.

Thanks for the others suggestions guys.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38790347
@COBOLdinosaur, too complicated for me, sorry...
;-)  At least give yourself a chance to learn -- read it and try to understand it.  And post a question or two about it.  But don't think that we are making this "hard on you."  It's not about you -- it's about the meets-minimum functional requirements necessary to demonstrate competence.
0
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 38790369
I agree with Ray in that looking at code will give you a chance to learn.  Ray and I are both teachers and IMHO, reading code and then modifying it to do what you want is a great way to learn.

You can ask new questions about that you don't understand.  Asking questions also helps learning.  On EE, it's better to ask closed ended questions.  (Teachers should ask open ended questions in a classroom but that's teaching...)

What I suggest you do is take my code (or some other code) and put it up on your website using a "test file name."  Then strip out what you don't need but be sure to test frequently as you make changes to make sure you haven't broken it.  (If you make small changes and you break the script, you know it's in the last change you made and if that change is small, easier to fix.)
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 38793716
Ray and I are both teachers

Yeah I used to do a little myself at CC where they are pretty eager, and some lecturing at University where they think they already know stuff.  Now just a guest appearance once in a while. Actually taught COBOL back in the ancient past as well.

Cd&
0
 

Author Closing Comment

by:joao_c
ID: 38793770
Thanks guys, solved the problem. :)
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Someone recently asked me about how to display a progress indicator on a page while an iframe is loading. And I remember when I first came across this myself. It was a bit tricky to get my head around, but really, it's very simple. The most impor…
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

758 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

22 Experts available now in Live!

Get 1:1 Help Now