How to Code PHP: New User Registration Scripts

Today I’m going to show you how to code a php login script and new user registration script. If none of this makes sense (read / watch) my:

Learn W3C HTML Tutorial

CSS Style HTML Tutorial

JavaScript Scripting Tutorial

MySQL SQL Statements Tutorial

How to Code PHP Tutorial

Yes, there is a lot to learn, but every tutorial includes a video tutorial for your viewing pleasure. So into the working code we go.


// Start output buffering. Allows you to send messages to the server, such as session_start(), with less restrictions


Here we are telling the browser that we are going to serve up some php code with the php opening brace <?php.

The first function I call ob_start(), turns output buffering on. To keep it simple, this function allows you to send messages to the server with less restrictions. I’m using it here to make session calls, but you could use it to send a string to the server and other such things. If you want more on this leave a comment below.

// Initialize a session.


Since this script is going to be registering new users and allowing the user to login, I need to create a new session and that is what this function does.

// Connects to the database


This line of code opens a connection with the database. The require_once is used to call code directly into a page, so that the page contains only HTML code. We do this to keep the page all nice and tidy.

Obviously, to make my job easier I’m writing all of the JavaScript and PHP on the page directly for presentation reasons. You should use the require_once() function instead.

This is the code from the file

// This file contains the database access information.

// This file also establishes a connection to MySQL and selects the database.

// Set the database access information as constants.

DEFINE (‘DB_USER’, ‘userid’);

DEFINE (‘DB_PASSWORD’, ‘password’);


DEFINE (‘DB_NAME’, ‘DatabaseName’);

Here we are creating constants in PHP. This is also a listing of information required to connect to a database. You need to supply in this script the userid, password, host address of your database and finally the database name.

You want the file to be stored in a directory outside of your root folder, so it can’t be accessed by anyone other than you. Unless you want a hacker to have your database password.

if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) {

mysql_connect() connects to the database, if you provided the right information and then stores a reference to the database in the variable $dbc.

if (!mysql_select_db (DB_NAME)) { // If it can’t select the database.

// Handle the error.

trigger_error(“Could not select the database!\n<br />MySQL Error: ” . mysql_error());


} // End of mysql_select_db IF.

Here the PHP code is checking if the database name supplied exists. If it doesn’t, an error is triggered and a warning message is sent to the browser.

Then the exit() function terminates the PHP script and the if statement block is closed with a closing curly brace }.

} else {

// Print a message to the user, and kill the script.

trigger_error(“Could not connect to MySQL!\n<br />MySQL Error: ” . mysql_error());



If it couldn’t connect to the MySQL Database we print an error message on the screen and exit from the PHP script like before.

// Create a function for escaping the data.

function escape_data ($data) {

// Address Magic Quotes.

if (ini_get(‘magic_quotes_gpc’)) {

$data = stripslashes($data);


The function ini_get() checks to see if Magic Quotes are activated on the PHP server. Magic Quotes automatically escape out quote marks entered in your PHP code. Quoting errors are very common in PHP. Here is an example that would through an error:

echo “He said, “I don’t know””;

As you can see the PHP interpreter wouldn’t know which double quote closed the string and would throw an error. You could escape out a double quote with a backslash like this \”.

The function stripslashes(), does just that. It deletes the slashes that the magic quotes function adds.

// Check for mysql_real_escape_string() support.

if (function_exists(‘mysql_real_escape_string’)) {

global $dbc; // Need the connection.

$data = mysql_real_escape_string (trim($data), $dbc);

} else {

$data = mysql_escape_string (trim($data));


// Return the escaped value.

return $data;

} // End of function.


// End of connecting to database


Here we are providing security from people sending potentially damaging query’s to our database. First we are checking that the function mysql_real_escape_string(), is available. If it is we run it on the form data.

We use the trim() function to eliminate white space from the beginning and end of the string. Then we return the data and close the PHP script with the closing brace.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”


<html xmlns=”” lang=”en” xml:lang=”en”>




<!– allcontent div completely surrounds all the other div’s on the screen –>

<div id=”allcontent”>

<!– header is where you would put your header images, title and menu’s –>

<div id=”header”>


Here is the start of our HTML code. I left off a lot of information that you definitely want to fill in, but I wanted this to be as brief as possible.

<!– The div that contains the login section for the page –>

<div id=”login”>


// Welcome the user (by name if they are logged in).

echo ‘<h1>Welcome’;

if (isset($_SESSION[‘first_name’])) {

echo “, {$_SESSION[‘first_name’]}!”;


echo ‘</h1>’;

PHP Drop Down Menu 3Here we are checking if we have session data set for the current visitor. If we do we greet them by printing their first name to the screen. I’ve included an image that represents what this box would look like. Note: you can also see a sneak peak at an upcoming tutorial using auto-updating drop down boxes. More on that later.

// Display links based upon the login status

// Checks that the user_id session variable is set and that your not currently on the logout.php page

if (isset($_SESSION[‘user_id’]) AND (substr($_SERVER[‘PHP_SELF’], -10) != ‘logout.php’)) {

echo ‘<a href=”logout.php”>Logout</a><br />

<a href=”change_password.php”>Change Password</a><br />’;

} else { // Not logged in.

echo ‘ <a href=”register.php”>Register</a><br />

<a href=”login.php”>Login to your account</a><br />

<a href=”forgot_password.php”>Forgot Password</a><br />’;



In this block of code we are checking if the user_id variable has been set in a previous visit. We are also checking that the visitor is not currently on the logout.php page. If both of these checks come back true then we place the link to the logout page.

We follow that up by placing a link to the change password page. I’ll cover what it does in a future article.

I finish off this block of code by providing links if the person isn’t logged in to their account and have no session data saved. I print the Register, Login, and Forgot Password links to the page.

</div> <!– This closes the sidebar div –>

<div id=”main”>


if (isset($_POST[‘submitted’])) { // Handle the form.

// Check for a first name. stripslasshes() strips any back slashes from the name

if (eregi (‘^[[:alpha:]\.\’ \-]{2,15}$’, stripslashes(trim($_POST[‘first_name’])))) {

// escape_data eliminates any extra spaces from the string

$fn = escape_data($_POST[‘first_name’]);

} else {

$fn = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter your first name!</font></p>’;


This is the code that will execute when the new user types in all of their information and clicks on submit. First we are checking if the submit button has been pressed.

With the eregi() function we are performing a regular expression test. This test is extremely simple in that it will except a first name if it is made up of any letters, periods, quotes, or hyphens as long as it is 2 to 15 characters in length. For more information on Regular Expressions see my Tutorial on them here.

I prefer to do this error checking with JavaScript, so that the visitor is immediately alerted of an error instead of after they click submit. This is a PHP tutorial though, so PHP is what I’ll use.

The following blocks of code perform the same actions as the one here so I’ll skip my description of them.

// Check for a last name.

if (eregi (‘^[[:alpha:]\.\’ \-]{2,30}$’, stripslashes(trim($_POST[‘last_name’])))) {

$ln = escape_data($_POST[‘last_name’]);

} else {

$ln = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter your last name!</font></p>’;


// Check for an email address.

if (eregi (‘^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$’, stripslashes(trim($_POST[’email’])))) {

$e = escape_data($_POST[’email’]);

} else {

$e = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid email address!</font></p>’;


// Check for a street.

$s = ($_POST[‘street’]);

// Check for a company

$cmp = ‘ ‘;

$cmp = $cmp . ($_POST[‘company’]);

// Check for a city.

if (eregi (‘^[[:alpha:]\.\’ \-]{2,25}$’, stripslashes(trim($_POST[‘city’])))) {

$c = escape_data($_POST[‘city’]);

} else {

$c = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid city!</font></p>’;


// Check for a state.

if (eregi (‘^((AL)|(AK)|(AS)|(AZ)|(AR)|(CA)|(CO)|(CT)|(DE)|(DC)|(FM)|(FL)|(GA)|(GU)|(HI)|(ID)|(IL)|(IN)|(IA)|(KS)|(KY)|(LA)|(ME)|(MH)|(MD)|(MA)|(MI)|(MN)|(MS)|(MO)|(MT)|(NE)|(NV)|(NH)|(NJ)|(NM)|(NY)|(NC)|(ND)|(MP)|(OH)|(OK)|(OR)|(PW)|(PA)|(PR)|(RI)|(SC)|(SD)|(TN)|(TX)|(UT)|(VT)|(VI)|(VA)|(WA)|(WV)|(WI)|(WY))$’, stripslashes(trim($_POST[‘state’])))) {

$st = escape_data($_POST[‘state’]);

} else {

$st = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid state!</font></p>’;


// Check for a zip code.

if (eregi (‘^[[:alnum:]]{4,5}$’, stripslashes(trim($_POST[‘zip’])))) {

$z = escape_data($_POST[‘zip’]);

} else {

$z = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid zip code!</font></p>’;


// Check for a phone number.

if (eregi (‘^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$’, stripslashes(trim($_POST[‘work_phone’])))) {

$ph = escape_data($_POST[‘work_phone’]);

} else {

$ph = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid phone number!</font></p>’;


// Check for a password and match against the confirmed password.

if (eregi (‘^[[:alnum:]]{4,20}$’, stripslashes(trim($_POST[‘password1’])))) {

if ($_POST[‘password1’] == $_POST[‘password2’]) {

$p = escape_data($_POST[‘password1’]);

} else {

$p = FALSE;

echo ‘<p><font color=”red” size=”+1″>Your password did not match the confirmed password!</font></p>’;


} else {

$p = FALSE;

echo ‘<p><font color=”red” size=”+1″>Please enter a valid password!</font></p>’;


if ($fn && $ln && $e && $p && $fn && $s && $c && $st && $z && $ph && $cmp) { // If everything’s OK.

If all of the information was entered correctly we move on to entering the new user into the database.

// Make sure the email address is available and not taken already.

$query = “SELECT user_id FROM users WHERE email=’$e'”;

$result = mysql_query ($query) or trigger_error(“Query: $query\n<br />MySQL Error: ” . mysql_error());

You see here how to query the database. With the query I’m asking the database to return all user_id’s that match the email that was just entered. If you don’t understand these query’s refer to my SQL tutorials.

if (mysql_num_rows($result) == 0) { // Email address is available.

$a = md5(uniqid(rand(), true));

If the email has not been taken, which we find out with this if statement, we execute the code between the curly braces.

Create the activation code, by generating a random number, with rand(), making sure the number is unique with uniqid and convert it into a 32 digit encrypted code with md5.

$query = “INSERT INTO users (email, pass, first_name, last_name, active, registration_date, street, city, state, zip, work_phone, company) VALUES (‘$e’, SHA(‘$p’), ‘$fn’, ‘$ln’, ‘$a’, NOW(), ‘$s’, ‘$c’, ‘$st’, ‘$z’, ‘$ph’, ‘$cmp’)”;

$result = mysql_query ($query) or trigger_error(“Query: $query\n<br />MySQL Error: ” . mysql_error());

We are inserting the new user into the database, along with all of their personal data. If the query worked properly everything’s great, if not then print out an error to the screen.

if (mysql_affected_rows() == 1) { // If it ran OK.

$body = “Thank you for registering at the User Registration New Think Tank site. To activate your account, please click on this link:\n\n”;

$body .= “” . mysql_insert_id() . “&y=$a”;

mail($_POST[’email’], ‘Registration Confirmation’, $body, ‘From:’);

echo ‘<br><br><h1>Thank you for registering! A confirmation email has been sent to your address. Please click on the link in that email in order to activate your account.</h1>’;


We are checking to see that one row has been changed, and if it has we know we added the new user. Alert them to their success and then send them an email that confirms the success.

} else { // If it did not run OK.

echo ‘<p><font color=”red” size=”+1″>You could not be registered due to a system error. We apologize for any inconvenience.</font></p>’;


} else { // The email address is not available.

echo ‘<p><font color=”red” size=”+1″>That email address has already been registered. If you have forgotten your password, use the link to have your password sent to you.</font></p>’;


} else { // If one of the data tests failed.

echo ‘<p><font color=”red” size=”+1″>Please try again.</font></p>’;


If they weren’t properly entered in the database, alert them to that fact.

// mysql_close(); // Close the database connection.

} // End of the main Submit conditional.


Close the database connection and the PHP code script. The following is basic HTML form information. I won’t go over it, because it should be self explanatory.


<form action=”register.php” method=”post”>


<p><b>First Name:</b> <input type=”text” name=”first_name” size=”15″ maxlength=”15″ value=”<?php if (isset($_POST[‘first_name’])) echo $_POST[‘first_name’]; ?>” /></p>

<p><b>Last Name:</b> <input type=”text” name=”last_name” size=”30″ maxlength=”30″ value=”<?php if (isset($_POST[‘last_name’])) echo $_POST[‘last_name’]; ?>” /></p>

<p><b>Email Address:</b> <input type=”text” name=”email” size=”40″ maxlength=”40″ value=”<?php if (isset($_POST[’email’])) echo $_POST[’email’]; ?>” /> </p>

<p><b>Company:</b> <input type=”text” name=”company” size=”40″ maxlength=”40″ value=”<?php if (isset($_POST[‘company’])) echo $_POST[‘company’]; ?>” /> </p>

<p><b>Street:</b> <input type=”text” name=”street” size=”40″ maxlength=”40″ value=”<?php if (isset($_POST[‘street’])) echo $_POST[‘street’]; ?>” /> </p>

<p><b>City:</b> <input type=”text” name=”city” size=”25″ maxlength=”25″ value=”<?php if (isset($_POST[‘city’])) echo $_POST[‘city’]; ?>” /> </p>

<p><b>State:</b> <input type=”text” name=”state” size=”2″ maxlength=”2″ value=”<?php if (isset($_POST[‘state’])) echo $_POST[‘state’]; ?>” /> <small>Use only the two letter initials</small></p>

<p><b>Zip Code:</b> <input type=”text” name=”zip” size=”5″ maxlength=”5″ value=”<?php if (isset($_POST[‘zip’])) echo $_POST[‘zip’]; ?>” /> </p>

<p><b>Phone:</b> <input type=”text” name=”work_phone” size=”12″ maxlength=”12″ value=”<?php if (isset($_POST[‘work_phone’])) echo $_POST[‘work_phone’]; ?>” /> </p>

<p><b>Password:</b> <input type=”password” name=”password1″ size=”20″ maxlength=”20″ /> <small>Use only letters and numbers. Must be between 4 and 20 characters long.</small></p>

<p><b>Confirm Password:</b> <input type=”password” name=”password2″ size=”20″ maxlength=”20″ /></p>


<div align=”center”><input type=”submit” name=”submit” value=”Register” /></div>

<input type=”hidden” name=”submitted” value=”TRUE” />






Well there is my tutorial on how to setup both a login system and a new user registration page with PHP. If you have any questions leave them below.

Till next time…

– Think Tank

18 Responses to “How to Code PHP: New User Registration Scripts”

  1. Is there any way to download the complete code?

  2. dan says:

    where do i have to place each part of the code?

  3. good stuff 😛 really enjoyed this article, i’ll read a little more on your website soon after im done with work! 😉

  4. Mark Vincent says:

    Wow! that really helps a lot men. Thank you so much! Do you have a tutorial on how to code the birthday in registration? the day of the birthday depends on the month and year. example, if the user choose february and the year is a leap year then the day must be 28 or 29, that kind of thing, you know what my point is. If you have that tutorial, will you please email me? I will really appreciate your help. Thank you!

  5. sapna soni says:

    thanks for the ggreat tutorials…..
    i hav a request, i want to know more about ob_start

    • admin says:

      Thank you for the request and the compliment 🙂 I’m going to completely redo my PHP tutorial in combination with JavaScript to make web apps using html5. I’ll see if I can cover your topic before then

  6. maha says:

    How many files are required to write this script .
    Your tutorial is great you have described each and everything in a good way Thanks…..

  7. maha says:

    I want to ask one thing more Did you have any tutorial On Designing chat Room…….??//

  8. Devendra says:

    Dear Derek
    i could not find download link could you help

Leave a Reply

Your email address will not be published.