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 {


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.


} 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.







<!– 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’;




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’)) {



} else { // Not logged in.


<a href=”login.php”>Login to your account</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”>



// 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


} else {

$fn = FALSE;



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’])))) {


} else {

$ln = FALSE;



// Check for an email address.

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


} else {

$e = FALSE;



// 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’])))) {


} else {

$c = FALSE;



// 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’])))) {


} else {

$st = FALSE;



// Check for a zip code.

if (eregi (‘^[[:alnum:]]{4,5}$’, stripslashes(trim($_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.



} else {

$ph = FALSE;




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



} else {

$p = FALSE;



} else {

$p = FALSE;



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.



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.


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’)”;


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.


$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.



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






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


} // 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.







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











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.