• 0

Registration/Login forms in PHP


Question

This is a web development course project. Basically, we're asked to implement a conference paper submission system using PHP and MySQL. We've already worked with databases before so that should be easy. So far, I have both the registration and login forms connected to a database. Everything works fine except that I still don't know if this is the best way to handle forms. I read a bunch articles but most of them were outdated, so.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Register</title>
</head>

<body>

<?php

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

		// Data entered by the user.
		$username = $_POST[username];
		$password = $_POST[password];

		// Create a connection to the database.
		$con = mysql_connect("localhost", "test", "test");

		// Select the database.
		if(!mysql_select_db("myReview", $con))
			exit(mysql_error());

		// Check if username already exists.
		if(mysql_fetch_array(mysql_query("SELECT * FROM Users 
								   WHERE username = '$username'", $con))) {}
		// Display error.			
		else 
		{

		      // Add author to the database.
		      mysql_query("INSERT INTO Users (username, password, type)
					   VALUES ('$username', '$password', 3)", $con); 								  
				echo "You are now a registered author. Please wait while we redirect you to the main page.";				
				// Redirect user to main page.
			}
			mysql_close($con);
		}
	}
        else
        {
	?>

<form method="post" action="">
	Username <input type="text" name="username"> <br>
	Password <input type="password" name="password"> <br>
	Email <input type="text" name="email"> <br>
	<input type="submit" name="register" value="Register"> 
</form>

<?php
}
>

</body>

</html>

Should I keep the form inside the same page (else part)? Or should I redirect the user to a different page after they submit the form? Same goes to the login page. What about after they log in? Do I just create a session and check for it at the top of each page? I still don't know which way to go when it comes to validation either.

The thing is, I already know the answer to most of these questions, I just need to know which way is the best.

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Yes, having it in one file is fine. For the login, yes create a session and use it to keep the login persistent across pages.

There are a few issues with the code:

- you've got no data sanitation, you're just sticking raw POST data into you're SQL queries, this'll allow SQL injection attacks!

- you're not checking whether queries were successful or not, you should be checking mysql_query() doesn't return false, e.g.

$res = mysql_query("SELECT * FROM `users`");
if (!$res) {
    //display error
    // you can echo mysql_error() and mysql_errno() to get information on what went wrong, though in a real life application you wouldn't output such information on a live website because it could easily aid hackers!
} else {
    //carry on
}

- to avoid SQL keyword issues it's good practice in my opinion to surround table/field names with backticks, e.g. SELECT `username`,`password` FROM `users` WHERE `id`=1;

- should the username already exist, the form is not redisplayed!

- there are no validation checks, nor any way of redisplaying the user's form data should any sort of problem occur to save them entering it all again or using the back button (note, for security reasons, never redisplay the password, force them to re-enter it! - redisplaying it means a plaintext copy will exist in the HTML!)

- I also personally like to always do a simple integrity check of forms incase of tampering and to reduce bugs - using isset() on each form field that should exist in the POST array, e.g.

$fieldMissing = false;
if (! isset($_POST['username'])) { $fieldMissing = true; }
...
if ($fieldMissing) { die('Error: form field missing'); }

If you were doing this in real life, I'd also be suggesting that you look into CSRF (cross-site request forgery) protection, but I wouldn't bother spending the time on it for this, though reading up on it is still a good idea when you have time!

Link to comment
Share on other sites

  • 0

Yes, having it in one file is fine. For the login, yes create a session and use it to keep the login persistent across pages.

There are a few issues with the code:

<snipped>

If you were doing this in real life, I'd also be suggesting that you look into CSRF (cross-site request forgery) protection, but I wouldn't bother spending the time on it for this, though reading up on it is still a good idea when you have time!

This is a very rough idea of how it should look like, I was mainly testing the connection to the database, so yes, I'm aware of most of the issues you mentioned, well, except for the backticks, I thought those were used to get away with badly named fields? Also, I haven't got to the validation part yet, I don't know, I was thinking AJAX? Or should I just stick with PHP?

Well, no, but I don't see why I shouldn't give it a read if I have the time. Thank you. :)

To add to what theblazingangel said:

Please don't store the password as plain text in the database, hash it with at least MD5 or SHA256/SHA512.

Yes, I realize that, thanks! :)

Link to comment
Share on other sites

  • 0

if this is to go on the internet then you'll need to validate using PHP, client based validation can't be relied on (as they could just disable it!). I alway as pass the login form back to the login script until the visitor has successfully logged in, then I send 'em to the default user page.

Link to comment
Share on other sites

  • 0

Unless you want your site to get hacked in 5 seconds I would suggest you add validation to the server side like mounty suggested. In addition to that you will want to sanitize the input before giving it over to MySQL or you risk creating an SQL injection site.

Eg:

$Username = $_POST["Username"];
$Password = $_POST["Password"];

//Validation
if (!preg_match("#[A-Z0-9_]+#i", $Username)) {
	echo "Username contains invalid characters, may only contain alphanumeric characters including underscores!";
	die();
}
if (!preg_match("#[A-Z0-9_]+#i", $Password)) {
	echo "Password contains invalid characters, may only contain alphanumeric characters including underscores!";
	die();
}
if (strlen($Password) &lt; 4) {
	echo "Password is too short, must be at least 4 characters.";
	die();
}

//Sanitization
$Username = mysql_real_escape_string($Username);
$Password = mysql_real_escape_string($Password);

//Insert into database

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.