PHP Login Script

Associate
Joined
29 May 2005
Posts
144
Hello. I have made the following registration section to my login, which appears to be working fine, its adding everything to the database as I intended. OK its not very secure and more validation is needed, but its good for the time being.

I'm trying to keep things simple so I can learn better, but from the examples I have come accross on the internet for the next part, checking if the username and password.. errr, well basically im lost, they go into encryption and all sorts, which makes me wanna poke my eyes out.

could anyone perhaps write me up the compairing code) or some pseudocode for the logging in section, to see if indeed we are authenticated or not. This doesn't need to be a highly secure system , its just for me learning. ;)

Thanks a lot - MoFish

Code:
<?

$errormsg = 'please fill in your registration details below';

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

 $name = $_POST['name'];
 $password = $_POST['password'];
 $location = $_POST['location'];
 $email = $_POST['email'];
 $query = "insert into `user_details` (`name`, `password`, `location`, `email`) values ('$name', '$password', '$location', '$email')";
 
	if ($name == "" || $password == "" || $location == "" || $email == "") {
	$errormsg = 'please fill in all the fields';
	} else {
					
		if (mysql_query($query)){
			$errormsg = 'thanks for registering ' . $name;
		} else {
			$errormsg = 'error adding to database';
		}
	}
}
	echo "<p style='background-color:FFFFCC; border: 1px dotted;'>$errormsg</p>";

	?>
 
Store the password using md5($password) or whatever your variable is for the password when a user signs up.

Then what my registration system does it selects username and password from the database where the username=$username (the username entered) and then after that is: AND password=MD5('".$password."') so that MySQL can read the md5 passwords.

Craig.
 
All you need to know about passing user-submitted data to the database:

www.php.net/mysql_real_escape_string

Contains good advice but it boils down to: run your variables through a function similar to this:

Code:
function quote_smart($value)
{
   // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   $value = mysql_real_escape_string($value);
   return $value;
}
What you're doing there is undoing PHP's frankly stupid magic_quotes function which escapes a seemingly random subset of characters and causes no end of problems, and then running the variables through mysql_real_escape_string() which will clean them up so that people can't use evil SQL injection techniques to fool MySQL into doing things you don't want it to :)

Also, robmiller has a good article on PHP security here - I recommend reading it :)


Now, to see if a password is correct...what you want is a login form for the username and password, and then in your code you want to query the database for any rows where the username and password match the submitted username and password. If you get exactly one row back then this means the user has submitted the correct login details, and you can then carry on and grant them access :)

Edit: And yup, you should encrypt passwords in the database. Just use md5() on the submitted password before inserting the username/password record, and then use md5() on the submitted password.

md5 is a hashing algorithm which produces a 32 character string by running the submitted string through an algorithm. There is no way (well, no quick way) to "reverse" the process and obtain a password from the hashed value, which is why it's secure - if someone gained access to your database they couldn't obtain the user's password.

Hope that wasn't too technical. Fire away :)
 
Last edited:
okay, the md5 thing confuzed me before, but I think I have that drilled into my brain now.
okay, i'll give this a go, and post back here tommorow with my code i produce. it will proberly be totally random and incorrect, but i'll give it my best shot.

thanks again for the help - ps Beansprout you a legend.
 
Last edited:
:o

It was a copy/paste/cut/post/run to Mock The Week job...was gonna copy/paste the func from the PHP manual, but decided to be nicer.

Infact, oops, still more errors in it :o
 
hello, again. i've tryed to incorperate the md5 thing, but am having a few problems. should i be adding the hash'd password to the database? right now i have the following code for my login script, has taken me all week lol. I finally gave up with the md5 thing before adding it to the loginck.php because I was totally lost and didnt know if i was doing this right. Am i on the right lines here?

Thanks again, mofish

you may find reading the code easyer from a paste bin as it is coloured. here are the links:

index1.php (registration page) http://mofish.pastebin.com/583493
login.php http://mofish.pastebin.com/583494
loginck.php http://mofish.pastebin.com/583495

index1.php (this is my registration page)
Code:
<?php
include 'includes/include.core.php';
?>

<html>
<head>
	<title>work please</title>
</head>

<body>
<?

$errormsg = 'please fill in your registration details below';

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

 $name = $_POST['name'];
 $password = $_POST['password'];
 $password = md5($password);

 $location = $_POST['location'];
 $email = $_POST['email'];
 $query = "insert into `user_details` (`name`, `password`, `location`, `email`) values ('$name', '$password', '$location', '$email')";
 
	if ($name == "" || $password == "" || $location == "" || $email == "") {
	$errormsg = 'please fill in all the fields';
	} else {
					
		if (mysql_query($query)){
			$errormsg = 'thanks for registering ' . $name;
		} else {
			$errormsg = 'error adding to database';
		}
	}
}
	echo "<p style='background-color:FFFFCC; border: 1px dotted;'>$errormsg</p>";

	?>

   <form action="index1.php" method="post">
   
     <table width="260" style="border: 1px dotted; background-color:#FFFFCC">
	 <tr>
   		 <td width="106">Nick Name</td>
   		 <td width="144"><input type="text" name="name"></td>
 	 </tr>
 	 <tr>
   		 <td width="106">Password</td>
   		 <td width="144"><input type="password" name="password"></td>
 	 </tr>
 	 <tr>
   		 <td width="106">Location</td>
   		 <td width="144"><select name="location" style="width:144px">
   		  					 <option>United Kingdom</option>
   		   					 <option>USA</option>
   						 </select>
   		 </td>
 	 </tr>
	  <tr>
   		 <td width="106">Email</td>
   		 <td width="144"><input type="text" name="email"></td>
 	 </tr>
  	
	 <tr>
   	     <td colspan="2"><input name="submit" type="submit"></td>
 	 </tr> 
    </table>
  </form>
	<?
?>
</body>
</html>

login.php
Code:
<html>
<head>
<title>login</title>
</head>

<body>

<form action="loginck.php" method="post">
<table border='0' cellspacing='0' cellpadding='0'>
 
  <tr> 
  	<td>Login ID</td> 
	<td><input type ='text' name='name' ></td>
  </tr>

  <tr> 
  	<td>Password</td> 
	<td><input type ='text' name='password' ></td>
  </tr>

  <tr>
  	 <td><input type='submit' value='Submit'> <input type='reset' value='Reset'></td>
  </tr>

  <tr> 
	<td><a href='signup.php'>Sign Up</a></td> 
	<td>Forgot Password</td>
  </tr>

</table>
</form>
</body>
</html>

loginck.php
Code:
<?php

// loginck.php - performs my login check, or should
include 'includes/include.core.php';
?>

<html>
<head>
<title>ahhhhh this is driving me mad</title>

</head>

<body>

<?
print_r($_POST);

$name = $_POST['name'];
$password = $_POST['password'];

$name=mysql_real_escape_string($name);
$password=mysql_real_escape_string($password);

if($rec=mysql_fetch_array(mysql_query("SELECT * FROM `user_details` WHERE name='$name' AND password ='$password'"))){
	if(($rec['name']==$name)&&($rec['password']==$password)){
	 include "includes/newsession.php";
     echo "<p>Successfully, logged in <a href='logout.php'>Log OUT</a><a href=welcome.php>Members only section</a>";
	} 
}else{
	session_unset();
	echo "Incorrect Login Details Entered<input type='button' value='Retry' onClick='history.go(-1)'>";
}
?>

</body>
</html>
 
should i be adding the hash'd password to the database?
Yup :)

Consequently you need to md5() all the password values before they are used with the database (either inserting, selecting or updating passwords).

So - it looks like on the registration page you are using md5(), but on the loginck.php page you aren't. You can change this:

Code:
$password=mysql_real_escape_string($password);

To this:

Code:
$password=md5($password);

You don't really need to use mysql_real_escape_string() if you're md5'ing a variable, because md5 will always output a 32-character string, regardless of what input it's given :)

Fun, eh :D
 
ah, was that easy huh ... was pretty damm close, just didn't know if what I was doing was on the right lines.

Thanks again beansprout. ;)
 
Last edited:
I'll stay in the same topic, althought its not about a login script, more layouts. I have the following layout, and am wondering the best way to go around inserting pages into the main section of my table. How exactly do I go about dynamically linking these pages in PHP, without using a massive if statement for each page? Really am unsure on how to go about linking them but am guessing I need to use POST or GET somehow .... not sure how though.

Any help would be appriciated :) *hi beansprout* :)

Thanks Again MoFish

INDEX.PHP( SORRY IM A MESSY CODER I THINKS ;))
Code:
</head>
<body>
<center>

<table class="MainTable" cellspacing="0px">
 <tr class="banner">
  <td height="100" colspan="2" class="TableSection">&nbsp;</td>
 </tr>
 
 <tr class="topbar" cellspacing="0px">
  <td colspan="2" align="right">
	<table width="100%" class="TableSection">
	 <tr>
	  	<td align="left"><?php include("topbar.php");?></td>
	  	<td align="right"><?php echo date('dS F Y');?></td>	 
	 </tr>
	</table>	
  </td>
 </tr>
 
 <tr>
  <td class="NavigationSection" cellspacing="0px">
	<table cellspacing="0px" width="120px" style="margin:5px;">
	  <?php include("navigation.php");?>
	</table>
  </td>
  
  <td class="MainBody" cellspacing="0px">
      <?php include("main.php"); ?>
  </td>
  
  <tr class="bottombar" cellspacing="0px">
  <td colspan="3" align="right">
	<table width="100%" class="Footer">
	 <tr>
	  	<td align="right">Copyright PGL</td>	 
	 </tr>
	</table>	
  </td>
 </tr>
  
</table>
</center>
</body>
</html>

NAVIGATION.PHP (TOTAL STAB IN THE DARK - But How Do I Call These :confused: )
Code:
  <ul>
    <li><a href="index.php?url=register.php">Register Account</a></li>
    <li><a href="index.php?url=login.php">Login</a></li>
  </ul>
 
Last edited:
I'm not sure what you mean, but you can put normal HTML code in a .php document as long as it's not within <?PHP (<?).

If you want to have it inside the <? then just do echo "<a href=""> </a>"; etc.

Craig.
 
i mean like linking pages, i dont want to link them just like html.

ive seen something like this used in the past 'index.php?url=register.php' but when i click this it isnt calling into my main section of the table where i want it to, actually when i click it, its doing nothing at all. how do i go around making these links so they are included?
 
Call index.php?page=foo to load the contents of foo.php into the main section.

Code:
<html>
<head>
<title>whatever</title>
</head>
<body>

<p>This is some kind of header or something i guess</p>

<?php

$page = preg_replace('/\W/si', '', $_GET['page']);

include('./'.$page.'.php');

?>

<p>This is a footer!</p>

</body>

</html>

Although I personally find it much nicer to either do the opposite (including a header/footer on each page) or use Smarty.
 
If you must do it that way, use an array containing allowed pages and check against in_array() or similar before loading a page or you'll run the risk of including pages you don't want to be included :)
 
As Beansprout said, you could do something like this:

Code:
<?php

$a = array($_GET['page']);

if (in_array("register", $a)) {
      include 'register.php';
}

if (in_array("login", $a)) {
      include 'login.php';
}

?>

With the above code if login or register is not after ?page= then it won't display anything. I tested it ;)

But if login or register IS after ?page= then it'll include the page / do whatever you tell it to.

Edit:
I just tried Robs script, and it's pretty safe, you can't navigate outside of the directory you're in. One problem with that is you can then include any file in the directory the script is in, which might not be very safe depending on what you have in the dir.

Craig.
 
Last edited:
That's the other way around to what I was thinking :D

Code:
$allowed = array("index","logout","register","error");

$page = $_GET['page'];

if(in_array($page,$allowed)){
   //Do includes, whatever
} else {
   echo 'Nonono. Bad person. Bad. I'm not doing anything with you not tonight, not never.';
}
 
Craig321 said:
As Beansprout said, you could do something like this:

Code:
<?php

$a = array($_GET['page']);

if (in_array("register", $a)) {
      include 'register.php';
}

if (in_array("login", $a)) {
      include 'login.php';
}

?>

With the above code if login or register is not after ?page= then it won't display anything. I tested it ;)

But if login or register IS after ?page= then it'll include the page / do whatever you tell it to.

Edit:
I just tried Robs script, and it's pretty safe, you can't navigate outside of the directory you're in. One problem with that is you can then include any file in the directory the script is in, which might not be very safe depending on what you have in the dir.

Craig.
Much more logical to do it the other way round..

And you can use the array index as a page id too..

Code:
<?php

$pages = array('index', 'home', 'usercp', 'register', 'etc');

if ((isset($_GET['pageid'])) && (array_key_exists($_GET['pageid'], $pages)) {
    include_once $pages[$_GET['pageid']] . 'php';
} else {
    include_once 'default.php';
}

?>

Whitelist is always the more secure method.
 
Back
Top Bottom