logo

PHP Confirm Registration Link

Add comment

This will be quick tutorial on how you can implement confirm registration link into your PHP application. This will not be anything fancy, just simple HTML and PHP to show you how this work and one way how it can be implemented.

File Structure Top

User Registration Link Folder Structure

Folder Structure

This image show simple file structure. We have folder includes that will hold some common files. Those files are bootstrap.php and db.php. bootstrap.php will just have two require statements so all files that are needed are first included in this file. Then bootstrap.php is included where those files are needed. db.php will be used, as you all know, for database connection. config.php will have some configuration data and index.php, login.php and register.php we’ll explore later.

Database Table Top

This is table schema that we’ll use.

CREATE TABLE IF NOT EXISTS `tutor_userconfstr` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) COLLATE utf8_bin NOT NULL,
  `conf_string` varchar(32) COLLATE utf8_bin NOT NULL,
  `confirmed` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

Bootstrap And Config Top

I’ll just copy/paste codes used here because they are as simple as possible and I really don’t think I need to explain them. They use basic PHP function and they are explained in plenty tutorials that are online. If you don’t know something about them use Google or ask me :) .

config.php Top

define('DB_HOST', 'localhost');

define('DB_USER_NAME', 'root');

define('DB_PASS', '');

define('DB_NAME', 'tutoriali');

db.php Top

if (($con = mysql_connect(DB_HOST, DB_USER_NAME, DB_PASS)) === false)
    die ('Could not connect to database.');

if (mysql_select_db(DB_NAME, $con) === false)
    die ('Could not select database.');

bootstrap.php Top

session_start();

require_once './config.php';

require_once './includes/db.php';

Home page Top

Now we’ll do index.php. At beginning we include our bootstrap.php so we have all required variables.  Then we’ll have two conditions. We’ll just leave them empty for now. We’ll add functionality to them later. In our HTML we have few conditions that will echo some messages that we’ll also explain later when we do our register.php and login.php. We have two forms on our site (one that will log you in and one that will register account). And if user is logged in, we have some block of code that will echo that he’s logged in. This is HTML with PHP.

require_once './includes/bootstrap.php';

if (isset($_GET['confirm'])) {

    //We'll do this later
}

if (isset($_GET['logout'])) {
    //We'll also do this later
}

?>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Config Link Tutorial</title>
    </head>

    <body>
        < ?php if (!isset($_SESSION['user'])) : ?>
        <div style="width: 300px; margin: 0px auto;">
            < ?php if (isset($error)) : ?>
            <span style="font-weight: bold; color: red;">< ?php echo $error; ?></span>
            < ?php endif; ?>
            < ?php if (isset($success)) : ?>
            <span style="font-weight: bold; color: green;">< ?php echo $success; ?></span>
            < ?php endif; ?>
            < ?php if (isset($_GET['mailError'])) : ?>
            <span style="font-weight: bold; color: red;">Your e-mail is not valid.</span>
            < ?php endif; ?>
            < ?php if (isset($_GET['error'])) : ?>
            <span style="font-weight: bold; color: red;">There was an error.</span>
            < ?php endif; ?>
            < ?php if (isset($_GET['success'])) : ?>
            <span style="font-weight: bold; color: green;">Check your e-mail.</span>
            < ?php endif; ?>
            <form action="register.php" method="post">
                <fieldset>
                    <legend>Register</legend>
                    <label for="email">E-mail</label>
                    <input type="text" name="email" value="" id="email" />
                </fieldset>
                <br />
                <input type="submit" name="register" value="Register" />
            </form>
            <br />
            OR
            <br />
            < ?php if (isset($_GET['noEmail'])) : ?>
            <span style="font-weight: bold; color: red;">E-mail does not exist.</span>
            < ?php endif; ?>
            < ?php if (isset($_GET['noConfirm'])) : ?>
            <span style="font-weight: bold; color: red;">You did not confirm your e-mail.</span>
            < ?php endif; ?>
            <form action="login.php" method="post">
                <fieldset>
                    <legend>Login</legend>
                    <label for="email">E-mail</label>
                    <input type="text" name="email" value="" id="email" />
                </fieldset>
                <br />
                <input type="submit" name="login" value="Login" />
            </form>
        </div>
        < ?php else : ?>
        You are loged in. <a href="?logout">Log out</a>.
        < ?php endif; ?>
    </body>
</html>

Registration Top

Now we we’ll build registration. Nothing to special. We’ll have simple e-mail check and if there is error redirect again to index.php with some error passed as GET attribute. If there are no errors we insert user into database. We generate some random string that we’ll use as an confirm string. That string is also e-mailed to user. If there are any error, user is redirected to index.php.

require_once './includes/bootstrap.php';

if (!isset($_POST['email']) || !preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $_POST['email'])) {
    header('Location: index.php?mailError');
    die();
}

$md5 = md5(time());

$sql = 'INSERT INTO `tutor_userconfstr` ( '
. '`email`, `conf_string`'
. ') '
. 'VALUES ( '
. "'%s', '%s' "
. ')';

if (!mysql_query(sprintf(
    $sql,
    mysql_real_escape_string($_POST['email']),
    $md5
))) {
    header('Location: index.php?error');
    die();
}

if (!mail($_POST['email'], 'Confirm string', sprintf(
    'http://demos.php4every1.com/userRegistrationLink/index.php?confirm=%s',
    $md5),
'From: test@test.com' . "\n"))
    header('Location: index.php?error');
else
    header('Location: index.php?success');

Confirming E-mail Top

This is part where user will confirm it’s e-mail. If you remember, at start we defined to if statements in index.php. Now we’ll use one of them. That is one where we check if we have confirm attribute passed as GET. If it’s true then we try to confirm e-mail. We do that by updating field confirmed from 0 to 1. If no fields where updated then this confirm string does not exist or user confirmed it already. This part of the code goes in if statement.

$sql = 'UPDATE `tutor_userconfstr` '
. 'SET `confirmed` = 1 '
. "WHERE `conf_string` = '%s'";

if (mysql_query(sprintf(
    $sql,
    mysql_real_escape_string($_GET['confirm'])
))) {
    if (mysql_affected_rows($con) < 1)
       $error = 'Confirmation string does not exist or you confirmed it before.';
    else
       $success = 'You confirmed your e-mail.';
}
else
    $error = 'Could not confirm.';

Logging in Top

This part is very easy. We just select row from table where email matches to e-mail that we got from request. If e-mail exist we check if confirmed field is 1. If that’s true we save users id to session.

require_once './includes/bootstrap.php';

if (!isset($_POST['email'])) {
    header('Location: index.php?noEmail');
    die();
}

$sql = 'SELECT `confirmed`, `id` '
. 'FROM `tutor_userConfStr` '
. "WHERE `email` = '%s'";

if (($result = mysql_query(sprintf(
    $sql,
    mysql_real_escape_string($_POST['email'])
))) === false) {
    header('Location: index.php?noEmail');
    die();
}

$row = mysql_fetch_object($result);

if ($row->confirmed === '0') {
    header('Location: index.php?noConfirm');
    die();
}

$_SESSION['user'] = $row->id;

header('Location: index.php');

Logging out Top

Now we'll use second if statement in index.php. This statement will just unset key user from session and that's all (that will log out user). This is code for that statement.

unset($_SESSION['user']);
$success = 'You are now loged out.';

Conclusion Top
This will conclude our tutorial. If you have any questions just leave a comment. You can download source here and check demo here.

Related Posts
  • 18.08.2009 -- Permissions Using Bitwise (2)
    This will be a quick tutorial on how to use bitwise operators in PHP to create permissions control. ...
  • 16.07.2009 -- Advanced PHP User Login (8)
    If you ever had a bank account you are familiar with TAN-s (Transaction Authentication Number). What...
  • 19.04.2009 -- Multi-query function (5)
    I needed a function that will take a string or a file and then split it into small SQL queries. I fo...
  • 13.04.2009 -- 5 useful functions (1)
    I would like to share with you a couple of functions that use a lot and I consider them quite useful...
  • 02.01.2010 -- Enable E-mail In PHP – Win (0)
    This will be a quick tutorial that will show you how to enable e-mail function in PHP on Windows....
  • 25.11.2009 -- Implementing Bitwise Permissions (0)
    Reader Freddy requested a tutorial about implementing bitwise permissions in real application. This ...
  • 16.10.2009 -- PHP DomDocument Tutorial (5)
    This will be a quick tutorial that will show you how to use PHP's DOMDocument to parse your XML so y...

logo

6 comments to “PHP Confirm Registration Link”

  1. I’m not quite sure that I understand you. You did not get confirmation e-mail or what? What do you want to change?

  2. Nettie Jonker says:

    Hello Marijan,

    The tutorial, is not working.
    When I register, the words of check your email are not seen.
    adres is by example http:www.namesite
    Or do I have to change here.
    When I check my email I confirm, but I lost “path” The email is in the database.
    you can see confirm is 1. But when I want to log in there stood , email doesn’t exit.
    I try a lot of things. I hope you recognize the problem. Thank you vere much.

  3. You should use SQL syntax like this
    $sql = 'INSERT INTO `tutor_userconfstr` ( '
    . '`email`, `conf_string`, `nameOfYouField` '
    . ') '
    . 'VALUES ( '
    . "'%s', '%s', '%s' "
    ')';

    Replace nameOfYourField with actual name of your field in database and not that now in sprintf you need to add variable that holds name.

    About quick validation I would check with regular expression if it contains only letters and if it’s length is 2+ characters. This is that simple regular expression
    /^[a-zA-Z]{2,}$/.

    It should work :) .

  4. Russ says:

    Marijan-

    No problem adding the fild “name” to the database. The error I’m getting is referencing the field in the sql query:

    $sql = ‘INSERT INTO `tutor_userconfstr` ( ‘
    . ‘`email`, `conf_string`’
    . ‘) ‘
    . ‘VALUES ( ‘
    . “‘%s’, ‘%s’ ”

    Not sure how to reference it. Also, do you have some quick validation for the name field?

    Thanks again for the help!
    . ‘)’;

  5. First you need to add it in phpMyAdmin or using MySQL command
    ALTER TABLE `tableName` ADD COLUMN `columnName` VARCHAR(50);.

    Then you have to add that field to your HTML code and add some validation to register.php and change your SQL so that it now inserts name with other data.

    I hope it helps :) .

  6. Russ says:

    Marijan-

    This is a great tutorial! I’m interested in adding a name field to the form and db – could you give me a quick pointer? Thanks!

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2010 php4every1.com