Adonis register form php. Creating a simple user registration system in PHP and MySQL

In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged-in users. Any other user not logged in will not be able to access the page.

Learn how to create a complete blog with PHP and MySQL database with my free course on YouTube.

The first thing we "ll need to do is set up our database.

Create a database called registration... In the registration database, add a table called users... The users table will take the following four fields.

  • username - varchar (100)
  • email - varchar (100)
  • password - varchar (100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

CREATE TABLE `users` (` id` int (11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar (100) NOT NULL,` email` varchar (100) NOT NULL, `password` varchar (100) NOT NULL) ENGINE = InnoDB DEFAULT CHARSET = latin1;

And that "s it with the database.

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www(if you are using wampp server).

Inside the folder registration, create the following files:

Open these files up in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the register.php file and paste the following code in it:

regiser.php:

Register

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

First is that our form "s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that "s why we are including it at the very top of the register.php file.

Notice also that we are including the errors.php file to display form errors. We will come to that soon.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:

* (margin: 0px; padding: 0px;) body (font-size: 120%; background: # F8F8FF;) .header (width: 30%; margin: 50px auto 0px; color: white; background: # 5F9EA0; text -align: center; border: 1px solid # B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px;) form, .content (width: 30%; margin: 0px auto; padding: 20px ; border: 1px solid # B0C4DE; background: white; border-radius: 0px 0px 10px 10px;) .input-group (margin: 10px 0px 10px 0px;) .input-group label (display: block; text-align: left ; margin: 3px;) .input-group input (height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray;) .btn (padding: 10px; font-size: 15px; color: white; background: # 5F9EA0; border: none; border-radius: 5px;) .error (width: 92%; margin: 0px auto; padding: 10px; border: 1px solid # a94442; color: # a94442; background: # f2dede; border-radius: 5px; text-align: left;) .success (color: # 3c7 63d; background: # dff0d8; border: 1px solid # 3c763d; margin-bottom: 20px; )

Now the form looks beautiful.

Let "s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.

Open server.php and paste this code in it:

server.php

Sessions are used to track logged in users and so we include a session_start () at the top of the file.

The comments in the code pretty much explain everything, but I "ll highlight a few things here.

The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.

All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

0) : ?>

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that "s it for registration. Let" s look at user login.

Login user

Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:

Registration system PHP and MySQL

Login

Not yet a member? Sign up

Everything on this page is quite similar to the register.php page.

Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:

// ... // LOGIN USER if (isset ($ _ POST ["login_user"])) ($ username = mysqli_real_escape_string ($ db, $ _POST ["username"]); $ password = mysqli_real_escape_string ($ db, $ _POST ["password"]); if (empty ($ username)) (array_push ($ errors, "Username is required");) if (empty ($ password)) (array_push ($ errors, "Password is required"); ) if (count ($ errors) == 0) ($ password = md5 ($ password); $ query = "SELECT * FROM users WHERE username =" $ username "AND password =" $ password ""; $ results = mysqli_query ($ db, $ query); if (mysqli_num_rows ($ results) == 1) ($ _SESSION ["username"] = $ username; $ _SESSION ["success"] = "You are now logged in"; header (" location: index.php ");) else (array_push ($ errors," Wrong username / password combination ");)))?>

Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.

Now let "s see what happens in the index.php file. Open it up and paste the following code in it:

Home

Home Page

Welcome

logout

The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you "d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.

The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.

Good day friends! Let's take a look at user registration in PHP with you. First, let's define the conditions for our user registration:

  • We encrypt the password using the algorithm MD5
  • The password will be "salted"
  • Check if Login is busy
  • User activation by letter.
  • Writing and storing data in MySQL DBMS

To write this script, we need to understand what user registration is. User registration is receiving data from a real user, processing and storing data.

If we explain in simple words, then registration is just the recording and storage of certain data by which we can authorize the user in our case - this is Login and Password.

Authorization is the granting of a certain person or group of persons the rights to perform certain actions, as well as the process of verifying these rights when trying to perform these actions. Simply put, using authorization, we can delimit access to one or another content on our website.

Let's consider the structure of the script directories for the implementation of our registration with authorization. We need to break the scripts into logical components. We have placed the registration and authorization modules in a separate directory. We will also place the connection to the database in separate directories. MySQL, file with custom functions, style file CSS and our template Html... This structure allows you to quickly navigate the scripts. Imagine you have a large site with a bunch of modules, etc. and if there is no order, it will be very difficult to find something in such a mess.

Since we will store all data in MySQL DBMS, then let's create a small table in which we will store registration data.

First, you need to create a table in the database. The table will be called bez_reg Where bez is the table prefix, and reg name of the table.

Table structure: bez_reg

- - Table structure `bez_reg` - CREATE TABLE IF NOT EXISTS` bez_reg` (`id` int (11) NOT NULL AUTO_INCREMENT,` login` varchar (200) NOT NULL, `pass` varchar (32) NOT NULL , `salt` varchar (32) NOT NULL,` active_hex` varchar (32) NOT NULL, `status` int (1) NOT NULL, PRIMARY KEY (` id`)) ENGINE = MyISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1;

Now let's create the main scripts for further work.

INDEX.PHP File

CONFIG.PHP File

"); ?>

404.html file

Error 404

Error 404

A 404 error occurred on the page

Return

BD.PHP File

INDEX.HTML File

PHP MySQL user registration with email activation

FUNCT.PHP File

"." \ n "; if (is_array ($ data)) (foreach ($ data as $ val) $ err. ="

  • ". $ val."
  • "." \ n ";) else $ err. ="
  • ". $ data."
  • "." \ n "; $ err. =""." \ n "; return $ err;) / ** Simple wrapper for MySQL queries * @param string $ sql * / function mysqlQuery ($ sql) ($ res = mysql_query ($ sql); / * Checking the result This shows the real query sent to MySQL, as well as the error. Convenient for debugging. * / if (! $ res) ($ message = "Invalid query:". mysql_error (). "\ n"; $ message. = "Query in full : ". $ sql; die ($ message);) return $ res;) / ** Simple salt generator * @param string $ sql * / function salt () ($ salt = substr (md5 (uniqid ()), - 8); return $ salt;)

    Let's get down to writing registration. First, we will need to make a registration form template so that the user can enter his data for processing. Next, we will need to write the form handler itself, which will check the entered user data for correctness. After the data has been successfully verified, we write them into our database and send a letter to the user to activate his account.

    REG.PHP file

    You have successfully registered! Please activate your account !!"; // Activate the account if (isset ($ _ GET [" key "])) (// Check the key $ sql =" SELECT * FROM `". BEZ_DBPREFIX. "Reg` WHERE` active_hex` = "". Escape_str ( $ _GET ["key"]). "" "; $ Res = mysqlQuery ($ sql); if (mysql_num_rows ($ res) == 0) $ err =" The activation key is not correct! "; // Check for errors and display to the user if (count ($ err)> 0) echo showErrorMessage ($ err); else (// Get the user's address $ row = mysql_fetch_assoc ($ res); $ email = $ row ["login"]; // Activate the account user $ sql = "UPDATE` ". BEZ_DBPREFIX." reg` SET `status` = 1 WHERE` login` = "". $ email. "" "; $ res = mysqlQuery ($ sql); // Send an email to activate $ title = "(! LANG: Your account on http: // site has been successfully activated"; $message = "Поздравляю Вас, Ваш аккаунт на http://сайт успешно активирован"; sendMessageMail($email, BEZ_MAIL_AUTOR, $title, $message); /*Перенаправляем пользователя на нужную нам страницу*/ header("Location:". BEZ_HOST ."less/reg/?mode=reg&active=ok"); exit; } } /*Если нажата кнопка на регистрацию, начинаем проверку*/ if(isset($_POST["submit"])) { //Утюжим пришедшие данные if(empty($_POST["email"])) $err = "Поле Email не может быть пустым!"; else { if(!preg_match("/^!} [email protected](+ \.) + (2,6) $ / i ", $ _POST [" email "])) $ err =" E-mail entered incorrectly "." \ N ";) if (empty ($ _ POST [ "pass"])) $ err = "The Password field cannot be empty"; if (empty ($ _ POST ["pass2"])) $ err = "The Confirm password field cannot be empty"; // Check for errors and display to the user if (count ($ err)> 0) echo showErrorMessage ($ err); else (/ * Continue checking the entered data Check passwords for matching * / if ($ _ POST ["pass"]! = $ _POST ["pass2" ]) $ err = "Passwords do not match"; // Check for errors and display it to the user if (count ($ err)> 0) echo showErrorMessage ($ err); else (/ * Check if we have such a user in the database * / $ sql = "SELECT` login` FROM `". BEZ_DBPREFIX. "reg` WHERE` login` = "". escape_str ($ _ POST ["email"]). "" "; $ res = mysqlQuery ($ sql); if (mysql_num_rows ($ res)> 0) $ err = "Sorry Login: ". $ _POST [" email "]." busy! "; // Check for errors and display it to the user if (count ($ err)> 0) echo showErrorMessage ($ err); else (// Get the HASH of the salt $ salt = salt (); // Salt the password $ pass = md5 (md5 ($ _ POST ["pass"]). $ salt); / * If all is well, write the data to the database * / $ sql = "INSERT INTO` ". BEZ_DBPREFIX." reg` VALUES ("", "" . escape_str ($ _ POST ["email"]). "", "". $ pass. "", "". $ salt. "", "". md5 ($ salt). "", 0) "; $ res = mysqlQuery ($ sql); // Sending an email to activate $ url = BEZ_HOST. "less / reg /? mode = reg & key =". md5 ($ salt); $ title = "(! LANG: Registration on http: / /website"; $message = "Для активации Вашего акаунта пройдите по ссылке ". $url .""; sendMessageMail($_POST["email"], BEZ_MAIL_AUTOR, $title, $message); //Сбрасываем параметры header("Location:". BEZ_HOST ."less/reg/?mode=reg&status=ok"); exit; } } } } ?>!}

    REG_FORM.HTML File

    PHP MySQL user registration with email activation

    Email *:
    Password *:
    Password Confirmation *:

    Fields with an icon * are required

    Since we are ready to register users, it's time to write an authorization. Let's create a form for user authorization, then write an authorization form handler and finally make a script show.php which will show us whether we are authorized in the system or not.

    AUTH.PHP file

    0) echo showErrorMessage ($ err); else (/ * Create a query to fetch from the database to check the authenticity of the user * / $ sql = "SELECT * FROM` ". BEZ_DBPREFIX." reg` WHERE `login` =" ". escape_str ($ _ POST [" email "]) . "" AND `status` = 1"; $ res = mysqlQuery ($ sql); // If the login matches, check the password if (mysql_num_rows ($ res)> 0) (// Get data from the table $ row = mysql_fetch_assoc ( $ res); if (md5 (md5 ($ _ POST ["pass"]). $ row ["salt"]) == $ row ["pass"]) ($ _SESSION ["user"] = true; // Reset parameters header ("Location:". BEZ_HOST. "Less / reg /? Mode = auth"); exit;) else echo showErrorMessage ("Wrong password!");) Else echo showErrorMessage ("Login ". $ _POST [" email "]." not found! ");))?>

    For those who have the latest PHP version, I post this script using PDO since expansion MySQL deprecated and removed from the newer PHP version. Download registration and authorization php mysql pdo

    The archive was updated on February 24, 2015.

    Attention: If you are using this script on a local server like DENWER,XAMPP, then you should not wait for letters to your mailbox. Letters are in a blank sendmail... IN Denwer you can find them along the way Z: \ tmp \! Sendmail \ you can open these files in any mail client.

    In order to divide site visitors into certain groups, a small system must be installed on the site php registration... Thus, you conditionally divide visitors into two groups of just random visitors and into a more privileged group of users to whom you give more valuable information.

    In most cases, a more simplified registration system is used, which is written in php in one file. register.php.

    So, we digress a little, and now we will take a closer look at the registration file.

    Register.php file

    So that it doesn't take a lot of your time, we will create a system that will collect users, taking minimal contact information from them. In this case, we will enter everything into the mysql database. For the maximum speed of the database, we will create the users table in the MyISAM format and in the utf-8 encoding.

    Note! All scripts must always be written in the same encoding. All site files and MySql database must be in the same encoding. The most common encodings are UTF-8 and Windows-1251.

    Why do you need to write everything in one encoding, we'll talk sometime later. Until then, take this information as the strictest rule of thumb for scripting otherwise there will be problems with scripting in the future. It's okay, of course, but you just waste a lot of time looking for errors in the script.

    How will the script itself work?

    We want to simplify everything and get quick results. Therefore, we will receive from users only login, email and password. And to protect against spam robots, we will install a small captcha. Otherwise, some boy from London will write a small robot parser that will fill the entire database with fake users in a few minutes, and will rejoice at his genius and impunity.

    Here is the script itself. Everything is written in one file register.php:

    ! `; // red question mark $ sha = $ sh. "scripts / pro /"; // path to main folder $ bg = `bgcolor =" # E1FFEB "`; // background color of lines?> Example of register script register.php style.css "/>

    In this case, the script refers to itself. And it is a form and a processor of the data entered in the form. Please note that the file is compressed in a zip archive and contains the config.php configuration file, the users database dump, the file containing the helper functions.php, the style.css stylesheet and the register.php file itself. There are also several files that are responsible for the operation and generation of captcha symbols.

    The process of creating a registration system is quite a lot of work. You need to write code to double-check the validity of email addresses, send confirmation emails, offer the ability to recover passwords, store passwords in a safe place, validate input forms, and much more. Even when you do all this, users will be reluctant to register, since even the most minimal registration requires their activity.

    In today's tutorial, we'll be developing a simple sign-up system that won't require you to use any passwords! As a result, we will get a system that can be easily modified or integrated into an existing PHP site. If you're interested, keep reading.

    PHP

    We are now ready to tackle the PHP code. The main functionality of the registration system is provided by the User class, which you can see below. The class uses (), which is a minimalist library for working with databases. The User class is responsible for accessing databases, generating login tokens and validating them. It presents us with a simple interface that can be easily incorporated into the registration system on your PHP-based sites.

    User.class.php

    // Private ORM instance
    private $ orm;

    /**
    * Find a user by a token string. Only valid tokens are taken into
    * consideration. A token is valid for 10 minutes after it has been generated.
    * @param string $ token The token to search for
    * @return User
    */

    Public static function findByToken ($ token) (

    // find it in the database and make sure the timestamp is correct


    -> where ("token", $ token)
    -> where_raw ("token_validity> NOW ()")
    -> find_one ();

    If (! $ Result) (
    return false;
    }

    Return new User ($ result);
    }

    /**
    * Either login or register a user.
    * @return User
    */

    Public static function loginOrRegister ($ email) (

    // If such a user already exists, return it

    If (User :: exists ($ email)) (
    return new User ($ email);
    }

    // Otherwise, create it and return it

    Return User :: create ($ email);
    }

    /**
    * Create a new user and save it to the database
    * @param string $ email The user "s email address
    * @return User
    */

    Private static function create ($ email) (

    // Write a new user to the database and return it

    $ result = ORM :: for_table ("reg_users") -> create ();
    $ result-> email = $ email;
    $ result-> save ();

    Return new User ($ result);
    }

    /**
    * Check whether such a user exists in the database and return a boolean.
    * @param string $ email The user "s email address
    * @return boolean
    */

    Public static function exists ($ email) (

    // Does the user exist in the database?
    $ result = ORM :: for_table ("reg_users")
    -> where ("email", $ email)
    -> count ();

    Return $ result == 1;
    }

    /**
    * Create a new user object
    * @param $ param ORM instance, id, email or null
    * @return User
    */

    Public function __construct ($ param = null) (

    If ($ param instanceof ORM) (

    // An ORM instance was passed
    $ this-> orm = $ param;
    }
    else if (is_string ($ param)) (

    // An email was passed
    $ this->
    -> where ("email", $ param)
    -> find_one ();
    }
    else (

    If (is_numeric ($ param)) (
    // A user id was passed as a parameter
    $ id = $ param;
    }
    else if (isset ($ _ SESSION ["loginid"])) (

    // No user ID was passed, look into the sesion
    $ id = $ _SESSION ["loginid"];
    }

    $ this-> orm = ORM :: for_table ("reg_users")
    -> where ("id", $ id)
    -> find_one ();
    }

    /**
    * Generates a new SHA1 login token, writes it to the database and returns it.
    * @return string
    */

    Public function generateToken () (
    // generate a token for the logged in user. Save it to the database.

    $ token = sha1 ($ this-> email.time (). rand (0, 1000000));

    // Save the token to the database,
    // and mark it as valid for the next 10 minutes only

    $ this-> orm-> set ("token", $ token);
    $ this-> orm-> set_expr ("token_validity", "ADDTIME (NOW ()," 0:10 ")");
    $ this-> orm-> save ();

    Return $ token;
    }

    /**
    * Login this user
    * @return void
    */

    Public function login () (

    // Mark the user as logged in
    $ _SESSION ["loginid"] = $ this-> orm-> id;

    // Update the last_login db field
    $ this-> orm-> set_expr ("last_login", "NOW ()");
    $ this-> orm-> save ();
    }

    /**
    * Destroy the session and logout the user.
    * @return void
    */

    Public function logout () (
    $ _SESSION = array ();
    unset ($ _ SESSION);
    }

    /**
    * Check whether the user is logged in.
    * @return boolean
    */

    Public function loggedIn () (
    return isset ($ this-> orm-> id) && $ _SESSION ["loginid"] == $ this-> orm-> id;
    }

    /**
    * Check whether the user is an administrator
    * @return boolean
    */

    Public function isAdmin () (
    return $ this-> rank () == "administrator";
    }

    /**
    * Find the type of user. It can be either admin or regular.
    * @return string
    */

    Public function rank () (
    if ($ this-> orm-> rank == 1) (
    return "administrator";
    }

    Return "regular";
    }

    /**
    * Magic method for accessing the elements of the private
    * $ orm instance as properties of the user object
    * @param string $ key The accessed property "s name
    * @return mixed
    */

    Public function __get ($ key) (
    if (isset ($ this-> orm -> $ key)) (
    return $ this-> orm -> $ key;
    }

    Return null;
    }
    }
    Tokens are generated using an algorithm and stored in the database. We use MySQL to set the token_validity column to 10 minutes. When validating a token, we tell the engine that we need a token, the token_validity field has not expired yet. Thus, we limit the time during which the token will be valid.

    Note that we are using the magic __get () method at the end of the document to access the properties of the user object. This allows us to access the data that is stored in the database in the form of properties: $ user-> email, $ user-> token. For example, let's see how we can use this class in the following code snippet:


    Another file that stores the necessary functionality is functions.php. There we have a few helper functions that allow us to keep the rest of the code tidy.

    Functions.php

    Function send_email ($ from, $ to, $ subject, $ message) (

    // Helper function for sending email

    $ headers = "MIME-Version: 1.0". "\ r \ n";
    $ headers. = "Content-type: text / plain; charset = utf-8". "\ r \ n";
    $ headers. = "From:". $ from. "\ r \ n";

    Return mail ($ to, $ subject, $ message, $ headers);
    }

    function get_page_url () (

    // Find out the URL of a PHP file

    $ url = "http". (empty ($ _ SERVER ["HTTPS"])? "": "s"). ": //". $ _ SERVER ["SERVER_NAME"];

    If (isset ($ _ SERVER ["REQUEST_URI"]) && $ _SERVER ["REQUEST_URI"]! = "") (
    $ url. = $ _SERVER ["REQUEST_URI"];
    }
    else (
    $ url. = $ _SERVER ["PATH_INFO"];
    }

    Return $ url;
    }

    function rate_limit ($ ip, $ limit_hour = 20, $ limit_10_min = 10) (

    // The number of login attempts for the last hour by this IP address

    $ count_hour = ORM :: for_table ("reg_login_attempt")
    ->
    -> where_raw ("ts> SUBTIME (NOW ()," 1:00 ")")
    -> count ();

    // The number of login attempts for the last 10 minutes by this IP address

    $ count_10_min = ORM :: for_table ("reg_login_attempt")
    -> where ("ip", sprintf ("% u", ip2long ($ ip)))
    -> where_raw ("ts> SUBTIME (NOW ()," 0:10 ")")
    -> count ();

    If ($ count_hour> $ limit_hour || $ count_10_min> $ limit_10_min) (
    throw new Exception ("Too many login attempts!");
    }
    }

    function rate_limit_tick ($ ip, $ email) (

    // Create a new record in the login attempt table

    $ login_attempt = ORM :: for_table ("reg_login_attempt") -> create ();

    $ login_attempt-> email = $ email;
    $ login_attempt-> ip = sprintf ("% u", ip2long ($ ip));

    $ login_attempt-> save ();
    }

    function redirect ($ url) (
    header ("Location: $ url");
    exit;
    }
    The rate_limit and rate_limit_tick functions allow us to limit the number of authorization attempts for a certain period of time. Authorization attempts are recorded in the reg_login_attempt database. These functions are triggered when the authorization form is submitted, as you can see in the following code snippet.

    The code below was taken from index.php and it is responsible for submitting the login form. It returns a JSON response, which is driven by the jQuery code we saw in assets / js / script.js.

    index.php

    If (! Empty ($ _ POST) && isset ($ _ SERVER ["HTTP_X_REQUESTED_WITH"])) (

    // Output a JSON header

    Header ("Content-type: application / json");

    // Is the email address valid?

    If (! Isset ($ _ POST ["email"]) ||! Filter_var ($ _ POST ["email"], FILTER_VALIDATE_EMAIL)) (
    throw new Exception ("Please enter a valid email.");
    }

    // This will throw an exception if the person is above
    // the allowed login attempt limits (see functions.php for more):
    rate_limit ($ _ SERVER ["REMOTE_ADDR"]);

    // Record this login attempt
    rate_limit_tick ($ _ SERVER ["REMOTE_ADDR"], $ _POST ["email"]);

    // Send the message to the user

    $ message = "";
    $ email = $ _POST ["email"];
    $ subject = "Your Login Link";

    If (! User :: exists ($ email)) (
    $ subject = "Thank You For Registering!";
    $ message = "Thank you for registering at our site! \ n \ n";
    }

    // Attempt to login or register the person
    $ user = User :: loginOrRegister ($ _ POST ["email"]);

    $ message. = "You can login from this URL: \ n";
    $ message. = get_page_url (). "? tkn =". $ user-> generateToken (). "\ n \ n";

    $ message. = "The link is going expire automatically after 10 minutes.";

    $ result = send_email ($ fromEmail, $ _POST ["email"], $ subject, $ message);

    If (! $ Result) (
    throw new Exception ("There was an error sending your email. Please try again.");
    }

    Die (json_encode (array (
    "message" => "Thank you! We \" ve sent a link to your inbox. Check your spam folder as well. "
    )));
    }
    }
    catch (Exception $ e) (

    Die (json_encode (array (
    "error" => 1,
    "message" => $ e-> getMessage ()
    )));
    }
    Upon successful authorization or registration, the above code sends an email to the person with a link for authorization. The token (token) is made available as the $ _GET variable "tkn" due to the generated URL.

    index.php

    If (isset ($ _ GET ["tkn"])) (

    // Is this a valid login token?
    $ user = User :: findByToken ($ _ GET ["tkn"]);

    // Yes! Login the user and redirect to the protected page.

    $ user-> login ();
    redirect ("protected.php");
    }

    // Invalid token. Redirect back to the login form.
    redirect ("index.php");
    }
    Running $ user-> login () will create the required session variables, allowing the user to remain logged in on subsequent logins.

    Logging out is implemented in approximately the same way:

    Index.php

    If (isset ($ _ GET ["logout"])) (

    $ user = new User ();

    If ($ user-> loggedIn ()) (
    $ user-> logout ();
    }

    Redirect ("index.php");
    }
    At the end of the code, we redirect the user to index.php again, so the? Logout = 1 parameter in the URL is excluded.

    Our index.php file will also need protection - we don't want already logged in users to see the form. For this we use the $ user-> loggedIn () method:

    Index.php

    $ user = new User ();

    if ($ user-> loggedIn ()) (
    redirect ("protected.php");
    }
    Finally, let's see how you can protect a page on your site and make it available only after authorization:

    protected.php

    // To protect any php page on your site, include main.php
    // and create a new User object. It "s that simple!

    require_once "includes / main.php";

    $ user = new User ();

    if (! $ user-> loggedIn ()) (
    redirect ("index.php");
    }
    After this check, you can be sure that the user has successfully logged in. You will also have access to the data stored in the database as properties of the $ user object. To display a user's email and their rank, use the following code:

    Echo "Your email:". $ User-> email;
    echo "Your rank:". $ user-> rank ();
    Here rank () is a method, since the rank column in the database usually contains numbers (0 for regular users and 1 for administrators), and we need to convert all of this to rank names, which is implemented using this method. To convert a regular user to an administrator, simply edit the user account in phpmyadmin (or any other database program). As an administrator, the user will not be endowed with any special features. You yourself have the right to choose which rights to grant administrators.

    Done!

    With this our simple registration system is ready! You can use it on an existing PHP site, or you can upgrade it to suit your own requirements.

    PHP | 25 Jan, 2017 | Clever techie

    In this lesson, we learn how to create user account registration form with PHP validation rules, upload profile avatar image and insert user data in MySQL database. We will then retrieve the information from the database and display it on the user profile welcome page. Here is what the welcome page is going to look like:

    Setting up Form CSS and HTML

    First, go ahead and copy the HTML source from below codepen and place the code in a file called form.php. Also create another file named form.css in the same directory and copy and paste all of the CSS code from the codepen below into it:

    Once you "ve saved form.php and form.css, you may go ahead and run form.php to see what the form looks like. It should look exactly the same as the one showing in the" Result "tab from the codepen above ...

    Creating the Database and Table

    Before we start adding PHP code to our form, let "s go ahead and create the database with a table which will store our registered users information in it. Below in the SQL script to create the database" accounts "and table" users ":

    CREATE DATABASE accounts; CREATE TABLE `accounts`.`users` (` id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR (100) NOT NULL,` email` VARCHAR (100) NOT NULL, `password` VARCHAR (100) NOT NULL,` avatar `VARCHAR (100) NOT NULL, PRIMARY KEY (` id`));

    Below is a complete code with error checking for connecting to MySQL database and running above SQL statements to create the database and users table:

    // connection variables $ host = "localhost"; $ user = "root"; $ password = "mypass123"; // create mysql connection $ mysqli = new mysqli ($ host, $ user, $ password); if ($ mysqli-> connect_errno) (printf ("Connection failed:% s \ n", $ mysqli-> connect_error); die ();) // create the database if (! $ mysqli-> query ("CREATE DATABASE accounts2 ")) (printf (" Errormessage:% s \ n ", $ mysqli-> error);) // create users table with all the fields $ mysqli-> query (" CREATE TABLE `accounts2`.`users` ( `id` INT NOT NULL AUTO_INCREMENT,` username` VARCHAR (100) NOT NULL, `email` VARCHAR (100) NOT NULL,` password` VARCHAR (100) NOT NULL, `avatar` VARCHAR (100) NOT NULL, PRIMARY KEY (`id`));") or die ($ mysqli-> error);

    With our HTML, CSS and the database table in place, we "re now reading to start working on our form. The first step is to create a place for error messages to show up and then we" ll start writing some form validation.

    Starting New Session for Error Messages

    Open up the form.php and add the following lines to it at the very top, make sure to use the php opening and closing tags (I have not included the html part of form.php to keep things clean).

    We have created new session because we "re going to need to access $ _SESSION [" message "] on the" welcome.php "page after user successfully registers. MySQL connection has also been created right away, so we can work with the database later on.

    We also need to print out $ _SESSION ["message"] on the current page. From the beginning the message is set to "" (empty string) which is what we want, so nothing will be printed at this point. Let "s go ahead and add the message inside the proper DIV tag:

    Creating Validation Rules

    This form already comes with some validation rules, the keyword "required" inside the HTML input tags, is checking to make sure the field is not empty, so we don "t have to worry about empty fields. Also, by setting input type to "email and" password ", HTML5 validates the form for proper email and password formatting, so we don" t need to create any rules for those fields either.

    However, we still need to write some validation rules, to make sure the passwords are matching, the avatar file is in fact an image and make sure the user has been added to our database.

    Let "s create another file and call it validate.php to keep things well organized. We" ll also include this file from our form.php.

    The first thing we "re going to do inside validate.php is to make sure the form is being submitted.

    / * validate.php * / // the form has been submitted with post method if ($ _SERVER ["REQUEST_METHOD"] == "POST") ()

    Then we "ll check if the password and confirm password are equal to each other

    if ($ _SERVER ["REQUEST_METHOD"] == "POST") (// check if two passwords are equal to each other if ($ _POST ["password"] == $ _POST ["confirmpassword"]) ())

    Working with Super Global Variables

    Note how we used super global variables $ _SERVER and $ _POST to get the information we needed. The keys names inside the $ _POST variable is available because we used method = "post" to submit our form.

    The key names are all the named HTML input fields with attribute name (eg: name = "password", name = "confirmpassword"):

    />

    To clarify a bit more, here is what the $ _POST would look like (assuming all the fields in the form have been filled out) if we used a print_r ($ _ POST) function on it, followed by die (); to terminate the script right after printing it. This is a good way of debugging your script and seeing what "s going on:

    if ($ _SERVER ["REQUEST_METHOD"] == "POST") (print_r ($ _ POST); die (); / * output: Array (=> clevertechie => [email protected]=> mypass123 => mypass123 => Register) * /

    Now we "re going to get the rest of our submitted values ​​from $ _POST and get them properly formatted so they can be inserted to our MySQL database table

    // the form has been submitted with post if ($ _SERVER ["REQUEST_METHOD"] == "POST") (if ($ _POST ["password"] == $ _POST ["confirmpassword"]) (// define other variables with submitted values ​​from $ _POST $ username = $ mysqli-> real_escape_string ($ _ POST ["username"]); $ email = $ mysqli-> real_escape_string ($ _ POST ["email"]); // md5 hash password for security $ password = md5 ($ _ POST ["password"]); // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ("images /".$_ FILES [" avatar "] [" name "]) ;))

    In the above code, we used real_escape_string () method to make sure our username, email and avatar_path are formatted properly to be inserted as a valid SQL string into the database. We also used md5 () hash function to create a hash string out of password for security.

    How File Uploading Works

    Also, notice the new super global variable $ _FILES, which holds the information about our image, which is the avatar being uploaded from the user "s computer. The $ _FILES variable is available because we used enctype =" multipart / form-data " in our form:

    Here is the output if we use the print_r ($ _ FILES) followed by die (); just like we did for the $ _POST variable:

    if ($ _SERVER ["REQUEST_METHOD"] == "POST") (print_r ($ _ FILES); die (); / * output: Array (=> Array (=> guldan.png => image / png => C: \ Windows \ Temp \ php18D8.tmp => 0 => 98823)) * / // this is how we "re able to access the image name: $ _FILES [" avatar "] [" name "]; // guldan. png

    When the file is first uploaded, using the post method, it will be stored in a temporary directory. That directory can be accessed with $ _FILES ["avatar"] ["tmp_name"] which is "C: \ Windows \ Temp \ php18D8.tmp" from the output above.

    We can then copy that file from the temporary directory, to the directory that we want which is $ avatar_path. But before we copy the file, we should check if the file is in fact image, for that we "ll check another key called from our $ _FILES variable.

    // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ("images /".$_ FILES [" avatar "] [" name "]); // make sure the file type is image if (preg_match ("! image!", $ _ FILES ["avatar"] ["type"])) (// copy image to images / folder if (copy ($ _ FILES [" avatar "] [" tmp_name "], $ avatar_path)) ())

    The preg_match function matches the image from the ["type"] key of $ _FILES array, we then use copy () function to copy our image file which takes in two parameters. The first one is the source file path which is our ["tmp_name"] directory and the second one is the destination path which is our "images / guldan.png" file path.

    Saving User Data in a MySQL Database

    We can now set some session variables which we "ll need on the next page, which are username and avatar_path, and we" ll also create the SQL query which will insert all the submitted data into MySQL database:

    if (copy ($ _ FILES ["avatar"] ["tmp_name"], $ avatar_path)) (// set session variables to display on welcome page $ _SESSION ["username"] = $ username; $ _SESSION ["avatar"] = $ avatar_path; // create SQL query string for inserting data into the database $ sql = "INSERT INTO users (username, email, password, avatar)". "VALUES (" $ username "," $ email "," $ password "," $ avatar_path ")";)

    The final step is turn our query, using the query () method and check if it "s successful. If it is, that means the user data has been saved in the" users "table successfully! We then set the final session variable $ _SESSION ["message"] and redirect the user to the welcome.php page using the header () function:

    // check if mysql query is successful if ($ mysqli-> query ($ sql) === true) ($ _SESSION ["message"] = "Registration succesful! Added $ username to the database!"; // redirect the user to welcome.php header ("location: welcome.php");)

    That "s pretty much all we need for the validation, we just need to add all the" else "keywords in case things don" t go as planned from all the if statements we have created. Here is what the full code for validate.php looks so far:

    / * validate.php * / // the form has been submitted with post if ($ _SERVER ["REQUEST_METHOD"] == "POST") (// two passwords are equal to each other if ($ _POST ["password"] == $ _POST ["confirmpassword"]) (// define other variables with submitted values ​​from $ _POST $ username = $ mysqli-> real_escape_string ($ _ POST ["username"]); $ email = $ mysqli-> real_escape_string ($ _POST ["email"]); // md5 hash password for security $ password = md5 ($ _ POST ["password"]); // path were our avatar image will be stored $ avatar_path = $ mysqli-> real_escape_string ("images /".$_FILES""avatar""""name "]); // make sure the file type is image if (preg_match ("! Image! ", $ _ FILES [" avatar "] [" type "])) (// copy image to images / folder if (copy ($ _ FILES ["avatar"] ["tmp_name"], $ avatar_path)) (// set session variables to display on welcome page $ _SESSION ["username"] = $ username; $ _SESSION ["avatar"] = $ avatar_path; // insert user data into database $ sql = "INSERT INTO users (username, email, password, avatar)". "VALUES (" $ use rname "," $ email "," $ password "," $ avatar_path ")"; // check if mysql query is successful if ($ mysqli-> query ($ sql) === true) ($ _SESSION ["message"] = "Registration successful!". "Added $ username to the database!"; / / redirect the user to welcome.php header ("location: welcome.php");)))))

    Setting Session Error Messages When Things Go Wrong

    Let "s go ahead and add all the else statements at once where we simply set the $ _SESSION [" message "] error messages which will be printed out when any of our if statements fail. Add the following code right after the last if statement where we checked for successful mysqli query and within the last curly bracket like this:

    If ($ mysqli-> query ($ sql) === true) ($ _SESSION ["message"] = "Registration succesful!". "Added $ username to the database!"; Header ("location: welcome.php" );) else ($ _SESSION ["message"] = "User could not be added to the database!";) $ mysqli-> close (); ) else ($ _SESSION ["message"] = "File upload failed!";)) else ($ _SESSION ["message"] = "Please only upload GIF, JPG or PNG images!";)) else ($ _SESSION [ "message"] = "Two passwords do not match!";)) // if ($ _SERVER ["REQUEST_METHOD"] == "POST")

    The session message will then display the error message in the div tag where we put our $ _SESSION ["message"] if you recall:

    Below is an example of what the error message is going to look like when two passwords don "t match. Feel free to play around with it to trigger other error messages:


    Creating User Profile Welcome Page

    We "re now done with the validate.php. The final step is to create welcome.php page which will display the username, avatar image and some users that have already been registered previously along with their own user names and mini avatar thumbnails. Here is what the complete welcome.php should look like, I will explain parts of it that may be confusing:

    ">
    Welcome query ($ sql); ?>
    All registered users:fetch_assoc ()) (echo "
    ". $ row [" username "]."
    "; echo"
    "; } ?>

    The $ _SESSION variable part from above should be easy to understand, we simply transfer over the variables from our validate.php page to this welcome.php page, if you "re still confused by that, please check out page for complete break down.

    Working with MySQL Result Object

    Whenever we use "SELECT" statement in our SQL query and then run that SQL with $ mysqli-> query ($ sql) command, the returned value is a MySQL result object. Once we have the result object, there are a few methods that become available so we can further start working with the data.

    $ sql = "SELECT username, avatar FROM users"; $ result = $ mysqli-> query ($ sql); // $ result = mysqli_result object

    One of those methods is $ result-> fetch_assoc () which fetches the current row and returns an array with all the row data. So we "re putting that in a conditional expression, which will become false when it reaches the last row in the result set, and storing the returned value from $ result-> fetch_assoc () inside the $ row variable.

    // returns associative array of fetched row while ($ row = $ result-> fetch_assoc ()) (echo "

    ". $ row [" username "]."
    "; echo"
    "; }

    Conclusion

    And that "s how we" re able to access $ row ["username"] and $ row ["avatar"] from the associative array that is being returned, of the users that have already been registered previously and live in our users database table!

    The profile welcome page should now look very similar to the one shown in the very beginning of this lesson, and the form is now complete, good job! Please post any questions you may have in the comments below.