Creating a registration form in html. Creating a simple user registration system in PHP and MySQL


Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register Your Full Name*: Email Address*: UserName*: Password*:

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() ( if(!isset($_POST["submitted"])) ( return false; ) $formvars = array(); if(!$this->ValidateRegistrationSubmission()) ( return false; ) $this- >CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) ( return false; ) if(!$this->SendUserConfirmationEmail($formvars)) ( return false; ) $this->SendAdminIntimationEmail($ formvars); return true; )

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) ( if(!$this->DBLogin()) ( $this->HandleError("Database login failed!"); return false; ) if(!$this->Ensuretable()) ( return false; ) if(!$this->IsFieldUnique($formvars,"email")) ( $this->HandleError("This email is already registered"); return false; ) if(!$this->IsFieldUnique( $formvars,"username")) ( $this->HandleError("This UserName is already used. Please try another username"); return false; ) if(!$this->InsertIntoDB($formvars)) ( $this->HandleError("Inserting to Database failed!"); return false; ) return true; )

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() ( $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ," "name VARCHAR(128) NOT NULL ," "email VARCHAR(64) NOT NULL ," " "phone_number VARCHAR(16) NOT NULL ," "username VARCHAR(16) NOT NULL ," "password VARCHAR(32) NOT NULL ," "confirmcode VARCHAR(32) ," "PRIMARY KEY (id_user)." ")"; if(!mysql_query($qry,$this->connection)) ( $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; ) return true; )

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) ( $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ​​("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $ this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query( $insert_query ,$this->connection)) ( $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; ) return true; )

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) ( $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]) ; $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email" ])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\ n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n." "$confirm_url\r \n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) ( $this-> HandleError("Failed sending registration confirmation email."); return false; ) return true; )

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub.

Welcome back!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

Instructions

Start creating a registration form with the tag, between which you need to place additional tags that allow users to enter their own data into the form.

Opening html file and start entering the code. The tag responsible for creating the form is “form”. We write down the tag along with the attributes “form action=”obrabotka.php” method=”post” name”forma1””. Let's start creating form elements. Almost all elements are made using the tag and its “type” attribute, which is responsible for the type of data, for example text, password, etc. We always set the name “name” to any of the attributes.

Enter: "br" Enter your name: "br"

"input type="text" name="fio""

"br" Enter password: "br"

"input type="password" name="pass""

"br"Enter E-mail:l"br"

"input type="text" name="email"".

Next, we create a radio button selection element. A radio button is a form element that, when you click on it with the cursor, other radio buttons are turned off. Let's explain with an example of our form. When ordering a course, the choice will consist of either CD or DVD, so you need to choose one. The element of the “type” attribute – “radio” is responsible for creating such a button. We will specify the same name for the media type, so we will specify the “value” attribute so that the handler can accurately determine the value of the variable. We write the code: "br"Select the storage medium option: "br"

"input type="radio" name="disc" value="cd"" CD "br"!}

"input type="radio" name="disc" value="dvd"" DVD "br"!}

If the “value” attribute is added to the text, then the form will immediately display the value that we assigned to this attribute. For example, so that the full name form already contains some kind of name (value = “name”).

Enter a different element and set type to "checkbox" to allow users to check more than one option on the form. For example:
(Contact me when shipped)
(Subscribe to )

Create a "Submit" button by typing tag and type equal to "submit", value set to "Submit". In addition, in another tag, make a “Reset” button, setting the type to “reset” and the value to “Reset”, respectively. For example, like this:


The Submit button is for submitting the data and the Reset button is for clearing the form if required.

Enter a closing tag to complete the form. Save the page.

Sources:

  • W3C Consortium website
  • product order form for the website

The registration form is a built-in module of the Joomla panel. You don't need to be an expert in web programming to add it. However, if you decide to change it, you can implement it using the Community Builder component or manually. You just need to edit the necessary elements by studying the basics of website building.

Instructions

Go to the administrative Joomla panel and open the built-in modules settings. Go to the “Advanced” tab and click on the “Create” button. The “Modules Manager” window will appear, in which you need to select and activate the registration form. Specify the desired title for the title and check the box next to the “Show title” line.

Open the "Initial text" section in the registration form module and edit the standard text for visitors if it does not suit you. In the “Login” item, you can choose how the user will be called on the site: under your name or login. Click the "Save" button for the changes to take effect.

Upload the Community Builder component to your site. To do this, go to the “Upload package file” section and click the “Browse” button. After selecting the required documents, click on the “Download and Install” button. Go to the admin panel and run the installed component.

Open the “Registration” tab and make all necessary changes to the registration form. This application very convenient to use, but if you want to change only one or two fields, it will be more convenient to edit manually.

Create a backup copy of the files that you will modify to make adjustments to the registration form. This will allow you to roll back all actions and restore the site to functionality in case of failure. Determine which fields you want to edit or add. For example, you want to add a “City” field to the registration form.

Open the default.php file, which is located at components/com_user/views/register/tmpl. Add a “Cities” display by inserting the appropriate HTML code into the registration form. To do this, you can copy any other item and edit it for the city. Make these changes to the jos_users table. Open the user.php file, which is located at libraries/joomla/database/table. Add a new variable to it. Save the settings and restart the site.

Sources:

  • how to change module in joomla
Tip 7: How to make a temporary registration without an owner

Happy new settlers are not always able to fulfill the requirement of the law on registration at the place of residence (make a temporary registration) within the established period of 90 days. Sometimes the reason for this may be the reluctance or inability of the apartment owner to appear at the relevant organization to carry out registration actions.

Of course, if the owner has not expressed a desire to legalize your temporary stay in his residential premises, then you will not be able to register. The exception is when you register your minor child at your place of registration. In this case, there is no need to obtain the owner's consent.

But if the problem with temporary registration is only the owner’s lack of desire to visit with you the employees responsible for accepting documents for registration, then the regulations provide for the opportunity to obtain temporary registration without the presence of the owner.

If the basis for moving in is a rental agreement, then you can send a notarial agreement by mail with the remaining documents attached (copy of passport, completed application). In such a situation, the persons responsible for accepting documents do not have the obligation to certify a copy of this agreement, and the owner of the premises does not sign the application.

If it is possible to submit only the agreement in simple written form, then the responsible persons are required to certify the signature of the owner and the registered person in the application. In this situation, the presence of the owner cannot be avoided.

A certificate of registration at the place of residence can also be obtained by mail.

Although the presence of the owner when obtaining temporary registration is not required, you should not hope that he will not find out about the new residents. After the registration actions have been completed, the FMS authorities will send him a notification about the person registered in his living space.

Tip 8: How to fill out the 3-NDFL form for selling a car

If you sold a car that you owned for more than three years, you don’t have to read any further: starting in 2011, your rights to a property tax deduction are automatically recognized. This means that you do not have to file a return. But if you have owned it for a shorter period of time, you will have to fill out the necessary papers. The easiest way to do this is using the Declaration program.

You will need

  • - computer;
  • - Internet access;
  • - “Declaration” program from GNIIVS of the Federal Tax Service of the Russian Federation;
  • - car purchase and sale agreement;
  • - documents confirming your other income and payment of personal income tax on it for the past year.

Instructions

You can download the latest version of the program on the website of the Main Research Center of the Federal Tax Service (GNIVC FTS) of Russia. It spreads

HTML forms s are complex interface elements. They include various functional elements: input fields and lists, tooltips, etc. All form code is contained within the .

Most web form information is conveyed using the . To enter one line of text, the element is used; for multiple lines, the element is used. The element creates a dropdown list.

The element creates labels for form fields. There are two ways to group labels and fields. If the field is inside an element, then the for attribute does not need to be specified.

Last Name Last Name Last Name

Form fields can be divided into logical blocks using the element. Each section can be given a name using the element.

Contact information Name Email
Rice. 1. Grouping form fields

To make the form more understandable to users, text is added to the form fields to provide an example of the input data. This type of text is called wildcard text and is created using the placeholder attribute.

Required fields must also be highlighted. Before HTML5, the asterisk * symbol was used next to the field name. The new specification introduces a special required attribute, which allows you to mark a required field at the markup level. This attribute instructs the browser (assuming it supports HTML5) not to send data after the user clicks submit until the specified fields are completed.

To change the appearance of a text field when receiving focus, use the focus pseudo-class. For example, you can make the background of the current field darker or add colored frame to make it stand out from the rest:

Input:focus ( background: #eaeaea; )

Another useful HTML5 attribute is the autofocus attribute. It allows you to automatically set focus to the desired initial field for elements and (only one element of each form).

Example of creating a registration form

HTML markup

Registration Name Gender male female E-mail Country Select country of residence Russia Ukraine Belarus Send

Note
action="form.php" - link to the form handler file. Create a file in UTF-8 encoding, upload it to the server and replace action="form.php" with the path to the file on your server.


Rice. 2. Default form appearance

As you can see from the figure, each form element has default browser styles. Let's clear the styles and style the form elements.

Form-wrap ( width: 550px; background: #ffd500; border-radius: 20px; ) .form-wrap *(transition: .1s linear) .profile ( width: 240px; float: left; text-align: center; padding : 30px; ) form ( background: white; float: left; width: calc(100% - 240px); padding: 30px; border-radius: 0 20px 20px 0; color: #7b7b7b; ) .form-wrap:after, form div:after ( content: ""; display: table; clear: both; ) form div ( margin-bottom: 15px; position: relative; ) h1 ( font-size: 24px; font-weight: 400; position: relative ; margin-top: 50px; ) h1:after ( content: "\f138"; font-size: 40px; font-family: FontAwesome; position: absolute; top: 50px; left: 50%; transform: translateX(-50 %); ) /********************** styling of form elements ******************** **/ label, span ( display: block; font-size: 14px; margin-bottom: 8px; ) input, input ( border-width: 0; outline: none; margin: 0; width: 100%; padding: 10px 15px; background: #e6e6e6; ) input:focus, input:focus ( box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); ) .radio label ( position: relative; padding-left: 50px; cursor: pointer; width: 50%; float: left; line-height: 40px; ) .radio input ( position: absolute; opacity: 0; ) .radio -control ( position: absolute; top: 0; left: 0; height: 40px; width: 40px; background: #e6e6e6; border-radius: 50%; text-align: center; ) .male:before ( content: " \f222"; font-family: FontAwesome; font-weight: bold; ) .female:before ( content: "\f221"; font-family: FontAwesome; font-weight: bold; ) .radio label:hover input ~ . radio-control, .radiol input:focus ~ .radio-control ( box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); ) .radio input:checked ~ .radio-control ( color: red; ) select ( width: 100%; cursor: pointer; padding: 10px 15px; outline: 0; border: 0; background: #e6e6e6; color: #7b7b7b; -webkit-appearance: none; /* uncheck webkit -browsers*/ -moz-appearance: none; /*uncheck in Mozilla Firefox*/ ) select::-ms-expand ( display: none; /*uncheck in IE*/ ) .select-arrow ( position: absolute ; top: 38px; right: 15px; width: 0; height: 0; pointer-events: none; /*activate the display of the list when you click on the arrow*/ border-style: solid; border-width: 8px 5px 0 5px; border-color: #7b7b7b transparent transparent transparent; ) button ( padding: 10px 0; border-width: 0; display: block; width: 120px; margin: 25px auto 0; background: #60e6c5; color: white; font-size: 14px; outline: none; text-transform : uppercase; ) /********************** add adaptability to the form ******************** **/ @media (max-width: 600px) ( .form-wrap (margin: 20px auto; max-width: 550px; width:100%;) .profile, form (float: none; width: 100%;) h1 (margin-top: auto; padding-bottom: 50px;) form (border-radius: 0 0 20px 20px;) )

Form.php file

Note
In the $subject variable, specify the text that will be displayed as the title of the letter;
Your_name - here you can specify the name that will be displayed in the “from whom the letter is from” field;
replace your_site_url with the address of the site with the registration form;
replace your_email with your email address;
$headers .= "Bcc: your_email". "\r\n"; sends BCC to your email address.

I bring to your attention a very simple and functional script for registration and authorization on the site, which consists of 3 PHP files with the connection of two java scripts, with the help of which errors are displayed in the form itself without reloading the page.

The script has been successfully tested on PHP 5.3.3 and PHP 5.6.3 versions.

What the script can do and has

  • Register new users;
  • Authorize users and record cookies for a certain period (no need to log in each time);
  • Show and hide certain information for authorized and unauthorized users, respectively;
  • Has an ADMIN PANEL where you can edit all data and delete users.

DEMO and Admin Panels are also there

STEP 1.
If you use the local registration and authorization script using DENWER, then you do not need to make changes to the files to connect to the database.
Otherwise, open the files: stayt.php, classes/Auth.class.php and adminka/connect.php, and at the very top replace the data for connecting to the database with yours.

STEP 2.
Go (if you use DENWER) to the address: http://localhost/Tools/phpmyadmin/, if on hosting, then click Databases and create a new database with the name: registr and comparison: utf8_general_ci.
You can, of course, set your own name, but then be sure to replace it in the files to connect to the database (see step 1).

STEP 3.
Click on the created registr database and then on the top SQL tab and in the input window that appears, paste this code and click OK. CREATE TABLE IF NOT EXISTS `my_users` (`id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `names` varchar(15) NOT NULL, `password` varchar(255) NOT NULL, `salt` varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8; All! Go to your address in the browser, try and experiment.

Admin panel

After you have completed at least one registration, you can go to the ADMIN section.
Login to the ADMIN PANEL:

http://your_site.ru/adminka/

Don't forget to secure this folder and you can also rename it.
When you open the Admin Panel, click the SEARCH button and all registered users will be displayed to you, where when you click on a specific ID number, you will see the user data for editing.

You can also quickly find a user by his E-mail; to do this, just enter a known e-mail in the SEARCH field and click on the button.
I do not recommend using the ADD button, since the user is added to the system without a password. And I have no idea why they even made it.

That's all, if it doesn't work out or isn't clear, ask questions.

At the same time you can try

Reg.ru: domains and hosting

The largest registrar and hosting provider in Russia.

More than 2 million domain names in service.

Promotion, domain mail, business solutions.

More than 700 thousand customers around the world have already made their choice.

*Mouse over to pause scrolling.

Back forward

Creating a simple user registration system in PHP and MySQL

Creating a registration system is a lot of work. You have to write code that validates email addresses, sends an email confirming registration, and also validates other form fields, and much more.

And even after you write all this, users will be reluctant to register, because... this requires some effort on their part.

In this tutorial, we will create a very simple registration system that does not require or store passwords at all! The result will be easy to modify and add to an existing PHP site. Want to find out how it works? Read below.



That's how our super simple system will work:

We will combine the authorization form and registration. This form will have a field for entering your email address and a registration button;
- When filling out the field with an email address, clicking on the registration button will create a record about a new user, but only if the entered email address was not found in the database.

After this, a random unique set of characters (token) is created, which is sent to the email specified by the user in the form of a link that will be relevant for 10 minutes;
- The link takes the user to our website. The system determines the presence of a token and authorizes the user;

Advantages of this approach:

There is no need to store passwords or validate fields;
- No need to recover your password, security questions etc.;
- From the moment a user registers/logs in, you can always be sure that this user will be in your access zone (that the email address is true);
- Incredibly simple registration process;

Flaws:

User account security. If someone has access to the user's mail, they can log in.
- Email is not secure and can be intercepted. Keep in mind that this question is also relevant in the case where the password has been forgotten and needs to be restored, or in any authorization system that does not use HTTPS for data transfer (login/password);
- While you configure your mail server properly, there is a chance that messages with authorization links will end up in spam;

Comparing the advantages and disadvantages of our system, we can say that the system has high usability (maximum convenience for the end user) and, at the same time, has a low security indicator.

So it is suggested to use it for registrations on forums and services that do not work with important information.

How to use this system

In case you just need to use a system to authorize users on your site, and you don’t want to take this lesson to pieces, here’s what you need to do:

You need to download the sources attached to the lesson
- Find the tables.sql file in the archive. Import it into your database using the import option in phpMyAdmin. Alternative way: open this file via text editor, copy the SQL query and execute it;
- Open includes/main.php and fill in the settings for connecting with your database (specify the user and password for connecting with the database, as well as the host and name of the database). In the same file, you must also specify the email, which will be used as the original address for messages sent by the system. Some hosts block outgoing emails unless the form contains a real email address, which was created from the host's control panel, so provide a real address;
- Upload all index.php , protected.php files and assets and includes folders via FTP to your host;
- Add the code below to each PHP page where you want to display the login form;

Require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )
- Ready!

For those who are interested in how it all works, read on below!

The first step is to write the HTM code for the authorization form. This code is located in the index.php file. This file also contains PHP code that processes form data and other useful features authorization systems. You can learn more about this in the section below dedicated to the PHP code review.

index.php

Tutorial: Super Simple Registration System With PHP & MySQL Login or Register

Enter your email address above and we will send
you a login link.

Login/Register

In the head section (between the and tags) I included the main styles (they are not covered in this tutorial, so you can look at them yourself. Folder assets/css/style.css). Before the closing tag, I included the jQuery library and the script.js file, which we will write and analyze below.


JavaScript

jQuery tracks the state of the "Register/Login" button using the function e.preventDefault() and sends AJAX requests. Depending on the server response, it displays one or another message and determines further actions/

assets/js/script.js

$(function())( var form = $("#login-register"); form.on("submit", function(e)( if(form.is(".loading, .loggedIn"))( return false ; ) var email = form.find("input").val(), messageHolder = form.find("span"); e.preventDefault(); $.post(this.action, (email: email), function (m)( if(m.error)( form.addClass("error"); messageHolder.text(m.message); ) else( form.removeClass("error").addClass("loggedIn"); messageHolder. text(m.message); ) )); )); $(document).ajaxStart(function())( form.addClass("loading"); )); $(document).ajaxComplete(function())( form. removeClass("loading"); )); ));

was added to the form to display the current state of the AJAX request (this was made possible thanks to the methods ajaxStart()) And ajaxComplete(), which you can find towards the end of the file).

This class displays a spinning animated GIF file (as if to hint to us that the request is being processed), and also acts as a flag to prevent the form from being submitted again (when the register button has already been clicked once). The .loggedIn class is another flag - it is set when the email was sent. This flag immediately blocks any further actions with the form.

Database schema

Our incredibly simple logging system uses 2 MySQL tables (the SQL code is in the tables.sql file). The first stores data about user accounts. The second stores information about the number of login attempts.


User table schema.

The system does not use passwords, as can be seen in the diagram. On it you can see the token column with tokens adjacent to the token_validity column. The token is installed as soon as the user connects to the system and sets his email to send a message (more on this in the next block). The token_validity column sets the time 10 minutes later, after which the token is no longer valid.


Table schema that counts the number of authorization attempts.

In both tables, the IP address is stored in processed form, using the ip2long function in a field of type integer.

Now we can write some PHP code. The main functionality of the system is assigned to the class User.class.php, which you can see below.

This class actively uses idorm (docs), these libraries are minimally necessary tools, for working with databases. It handles database access, token generation, and token validation. It provides a simple interface that makes it easy to connect a registration system to your site if it uses PHP.

User.class.php

Class User( // Private ORM case private $orm; /** * Find a user by token. Only valid tokens are accepted for consideration. The token is generated only for 10 minutes from the moment it was created * @param string $token. This is the one we are looking for token * @return User Return the value of the User function */ public static function findByToken($token)( // find the token in the database and make sure the correct timestamp is set $result = ORM::for_table("reg_users") ->where ("token", $token) ->where_raw("token_validity > NOW()") ->find_one(); if(!$result)( return false; ) return new User($result); ) /** * Authorize or register a user * @param string $email. User email address * @return User */ public static function loginOrRegister($email)( // If such a user already exists, return the value of the User function from the specified email address stored in the database if(User::exists($email))( return new User($email); ) // Otherwise, create a new user in the database and return the value of the User::create function from the specified email return User::create($email ); ) /** * Create a new user and save to the database * @param string $email. User email address * @return User */ private static function create($email)( // Write a new user and return the result of the User function from these values ​​$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 the Boolean value of the variable * @param string $email. User 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 instance $param ORM , id, email or 0 * @return User */ public function __construct($param = null) ( if($param instanceof ORM)( // ORM check passed $this->orm = $param; ) else if(is_string($param))( // Email check passed $this->orm = ORM::for_table ("reg_users") ->where("email", $param) ->find_one(); ) else( $id = 0; if(is_numeric($param))( // the value of the variable $param is passed to the user identifier $id = $param; ) else if(isset($_SESSION["loginid"]))( // Otherwise, see session $id = $_SESSION["loginid"]; ) $this->orm = ORM::for_table( "reg_users") ->where("id", $id) ->find_one(); ) ) /** * Generate a new SHA1 authorization token, writes it to the database and returns its value * @return string */ public function generateToken( )( // Generate a token for an authorized user and save it to the database $token = sha1($this->email.time().rand(0, 1000000)); // Save the token in the database // And mark it so that it is only valid for the next 10 minutes $this->orm->set("token", $token); $this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")"); $this->orm->save(); return $token; ) /** * Authorize the user * @return void */ public function login())( // Mark the user as logged in $_SESSION["loginid"] = $this->orm->id; // Update the value of the last_login database field $this->orm->set_expr("last_login", "NOW()"); $this->orm->save(); ) /** * Destroy the session and log out the user * @return void */ public function logout ()( $_SESSION = array(); unset($_SESSION); ) /** * Check if the user is logged in * @return boolean */ public function loggedIn())( return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id; ) /** * Checks whether the user is an administrator * @return boolean */ public function isAdmin())( return $this->rank() = = "administrator"; ) /** * Find the user type, can be either administrator or regular * @return string */ public function rank())( if($this->orm->rank == 1)( return "administrator" "; ) return "regular"; ) /** * Method that allows you to get the user's private information as * properties of the User object * @param string $key The name of the property that gets access * @return mixed */ public function __get($key)( if(isset($this->orm->$key))( return $this->orm->$key; ) return null; ) )

Tokens are generated using the SHA1 algorithm and stored in the database. I'm using MySQL's timing functions to set a 10-minute time limit for a token's validity.

When a token is validated, we directly tell the handler that we are only considering tokens that have not yet expired, stored in the token_validity column.

Please note that I am using the magic method __get docs library at the end of the file to intercept access to the properties of the User object.

Thanks to this, it becomes possible to access information stored in the database thanks to the properties $user->email, $user->token, etc. In the next code fragment, we will look at how to use these classes as an example.


Protected page

Another file that stores useful and necessary functionality is the functions.php file. There are several so-called helpers - assistant functions that allow you to create cleaner and more readable code in other files.

functions.php

Function send_email($from, $to, $subject, $message)( // Helper that sends 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())( // Determine the URL of the 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)( // Number of login attempts in the last hour to this IP address $count_hour = ORM: :for_table("reg_login_attempt") ->where("ip", sprintf("%u", ip2long($ip))) ->where_raw("ts > SUBTIME(NOW(),"1:00")") ->count(); // Number of login attempts in the last 10 minutes at 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 new entry in the table that counts the number of login attempts $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; )

Functions rate_limit And rate_limit_tick monitor the number of authorization attempts over the elapsed period of time since the first attempt. The login attempt is recorded in the database in the reg_login_attempt column. These functions are called when the form data is processed and submitted as you can see from the following code snippet.

The code below is taken from the index.php file and it handles the form submission. It returns a JSON response, which in turn is processed by jQuery in the assets/js/script.js file that we looked at earlier.

index.php

Try( if(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"]))( // Output a JSON header header("Content-type: application/json"); // Is this email address valid if(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))( throw new Exception("Please enter a valid email."); ) // Check. Is the user allowed to log in, has he exceeded the number of allowed connections? (functions.php file for more information) rate_limit($_SERVER["REMOTE_ADDR"]); // Log this login attempt rate_limit_tick($_SERVER["REMOTE_ADDR"], $ _POST["email"]); // Send an email 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 authorize or register a user $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 to 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()))); )

After successful login/registration, the code above will send the user a login link. The token becomes available because it is passed as a variable in the generated link by the method $_GET with tkn marker

index.php

If(isset($_GET["tkn"]))( // Is this token valid for authorization? $user = User::findByToken($_GET["tkn"]); if($user)( // Yes , is. Redirect to a protected page $user->login(); redirect("protected.php"); ) // No, the token is not valid. Redirect to a page with an authorization/registration form redirect("index.php "); )

$user->login()

will create the necessary variables for the session, so that the user, viewing subsequent pages of the site, will remain authorized at all times.

The processing of the function to exit the system is arranged in a similar way.

index.php

If(isset($_GET["logout"]))( $user = new User(); if($user->loggedIn())( $user->logout(); ) redirect("index.php") ; )

At the end of the code, I again set a redirect to index.php, so the parameter ?logout=1 transmitted via URL is not required.

Our index.php file requires additional. protection - we don't want people who have logged into the system to see the registration form again. For these purposes, we use the method $user->loggedIn().

index.php

$user = new User(); if($user->loggedIn())( redirect("protected.php"); )

Finally, here is a piece of code that allows you to protect the pages of your site and make it accessible only after authorization.

protected.php

// To protect every page on your site, include a main.php file // and create a new User object. That's how easy it is! require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )

After this check, you can be sure that the user was successfully authorized. You can also access stored information in the database using object properties $user. To display the user's email and status, use this code:

Echo "Your email: ".$user->email; echo "Your rank: ".$user->rank();

Method rank() is used here because the database usually stores numbers (0 for a regular user, 1 for an administrator) and we need to convert this data into the statuses to which they belong, which is what this method helps us with.

To make a regular user an administrator, simply edit the user entry through phpMyAdmin (or any other program that allows you to manage databases). The administrator status does not give any privileges; in this example, the page will display that you are an administrator - and that’s it.

But what to do with this is left to your discretion; you can write and compose code yourself that sets certain privileges and capabilities for administrators.

We're done!

We're done with this incredibly super quasi simple shape! You can use it in your PHP sites, it's quite simple. You can also modify it for yourself and make it the way you want.

The material was prepared by Denis Malyshok specifically for the website

P.S. Do you want to move further in mastering PHP and OOP? Pay attention to premium lessons on various aspects of website building, including programming in PHP, as well as a free course on creating your own CMS system in PHP from scratch using OOP:

Did you like the material and want to thank me?
Just share with your friends and colleagues!








2024 gtavrl.ru.