Создаем невероятную простую систему регистрации на PHP и MySQL. Создание и проверка форм Юродивый registration form php


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 ("$username", "$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.

Much of the websites have a registration form for your users to sign up and thus may benefit from some kind of privilege within the site. In this article we will see how to create a registration form in PHP and MySQL.

We will use simple tags and also we will use table tag to design the Sign-Up.html webpage. Let’s start:

Listing 1 : sign-up.html

Sign-Up

Registration Form
Name
Email
UserName
Password
Confirm Password


Figure 1:

Description of sing-in.html webpage:

As you can see the Figure 1, there is a Registration form and it is asking few data about user. These are the common data which ask by any website from his users or visitors to create and ID and Password. We used table tag because to show the form fields on the webpage in a arrange form as you can see them on Figure 1. It’s looking so simple because we yet didn’t used CSS Style on it now let’s we use CSS styles and link the CSS style file with sing-up.html webpage.

Listing 2 : style.css

/*CSS File For Sign-Up webpage*/ #body-color{ background-color:#6699CC; } #Sign-Up{ background-image:url("sign-up.png"); background-size:500px 500px; background-repeat:no-repeat; background-attachment:fixed; background-position:center; margin-top:150px; margin-bottom:150px; margin-right:150px; margin-left:450px; padding:9px 35px; } #button{ border-radius:10px; width:100px; height:40px; background:#FF00FF; font-weight:bold; font-size:20px; }

Listing 3 : Link style.css with sign-up.html webpage



Figure 2:

Description of style.css file:

In the external CSS file we used some styles which could be look new for you. As we used an image in the background and set it in the center of the webpage. Which is become easy to use by the help of html div tag. As we used three div tag id’s. #button, #sing-up, and #body-color and we applied all CSS styles on them and now you can see the Figure 2, how much it’s looking beautiful and attractive. You can use many other CSS styles as like 2D and 3D CSS styles on it. It will look more beautiful than its looking now.

After these all simple works we are now going to create a database and a table to store all data in the database of new users. Before we go to create a table we should know that what we require from the user. As we designed the form we will create the table according to the registration form which you can see it on Figure 1 & 2.

Listing 3 : Query for table in MySQL

CREATE TABLE WebsiteUsers (userID int(9) NOT NULL auto_increment, fullname VARCHAR(50) NOT NULL, userName VARCHAR(40) NOT NULL, email VARCHAR(40) NOT NULL, pass VARCHAR(40) NOT NULL, PRIMARY KEY(userID));

Description of Listing 3:

One thing you should know that if you don’t have MySQL facility to use this query, so should follow my previous article about . from this link you will able to understand the installation and requirements. And how we can use it.

In the listing 3 query we used all those things which we need for the registration form. As there is Email, Full name, password, and user name variables. These variable will store data of the user, which he/she will input in the registration form in Figure 2 for the sing-up.

After these all works we are going to work with PHP programming which is a server side programming language. That’s why need to create a connection with the database.

Listing 4 : Database connection

Description of Listing 4:

We created a connection between the database and our webpages. But if you don’t know is it working or not so you use one thing more in the last check listing 5 for it.

Listing 5 : checking the connection of database connectivity

Description Listing 5:

In the Listing 5 I just tried to show you that you can check and confirm the connection between the database and PHP. And one thing more we will not use Listing 5 code in our sing-up webpage. Because it’s just to make you understand how you can check the MySQL connection.

Now we will write a PHP programming application to first check the availability of user and then store the user if he/she is a new user on the webpage.

Listing 6 : connectivity-sign-up.php

Description of connectivity-sign-up.php

In this PHP application I used simplest way to create a sign up application for the webpages. As you can see first we create a connection like listing 4. And then we used two functions the first function is SignUP() which is being called by the if statement from the last of the application, where its first confirming the pressing of sign up button. If it is pressed then it will call the SingUp function and this function will use a query of SELECT to fetch the data and compare them with userName and email which is currently entered from the user. If the userName and email is already present in the database so it will say sorry you are already registered

If the user is new as its currently userName and email ID is not present in the database so the If statement will call the NewUser() where it will store the all information of the new user. And the user will become a part of the webpage.



Figure 3

In the figure 3, user is entering data to sign up if the user is an old user of this webpage according to the database records. So the webpage will show a message the user is registered already if the user is new so the webpage will show a message the user’s registration is completed.



Figure 4:

As we entered data to the registration form (Figure 4), according to the database which userName and email we entered to the registration form for sing-up it’s already present in the database. So we should try a new userName and email address to sign-up with a new ID and Password.



Figure 5

In figure 5, it is confirming us that which userName and email id user has entered. Both are not present in the database records. So now a new ID and Password is created and the user is able to use his new ID and Password to get login next time.

Conclusion:

In this article we learnt the simplest way of creating a sign up webpage. We also learnt that how it deals with the database if we use PHP and MySQL. I tried to give you a basic knowledge about sign up webpage functionality. How it works at back end, and how we can change its look on front end. For any query don’t hesitate and comment.

Для того, чтобы разделить посетителей сайта на некие группы на сайте обязательно устанавливают небольшую систему регистрации на php . Таким образом вы условно разделяете посетителей на две группы просто случайных посетителей и на более привилегированную группу пользователей, которым вы выдаете более ценную информацию.

В большинстве случаев, применяют более упрощенную систему регистрации, которая написана на php в одном файле register.php .

Итак, мы немного отвлеклись, а сейчас рассмотрим более подробно файл регистрации.

Файл register.php

Для того, чтобы у вас это не отняло массу времени создадим систему, которая будет собирать пользователей, принимая от них минимальную контактную информацию. В данном случае все будем заносить в базу данных mysql. Для наибольшей скорости работы базы, будем создавать таблицу users в формате MyISAM и в кодировке utf-8.

Обратите внимание! Писать все скрипты нужно всегда в одной кодировке. Все файлы сайта и база данных MySql должны быть в единой кодировке. Самые распространенные кодировки UTF-8 и Windows-1251.

Для чего нужно писать все в одной кодировке мы поговорим как-нибудь попозже. А пока примите эту информацию как строжайшее правило создания скриптов иначе в будущем возникнут проблемы с работой скриптов. Ничего страшного, конечно, но просто потеряете массу времени для поиска ошибок в работе скрипта.

Как будет работать сам скрипт?

Мы хотим все упростить и получить быстрый результат. Поэтому будем получать от пользователей только логин, email и его пароль. А для защиты от спам-роботов, установим небольшую капчу. Иначе какой-нибудь мальчик из Лондона напишет небольшой робот-парсер, который заполнит всю базу липовыми пользователями за несколько минут, и будет радоваться своей гениальности и безнаказанности.

Вот сам скрипт. Все записано в одном файле register.php :

! `; // красный вопросительный знак $sha=$sh."scripts/pro/"; //путь к основной папке $bg=` bgcolor="#E1FFEB"`; // фоновый цвет строк?> Пример скрипта регистрации register.php style.css" />

В данном случае скрипт обращается к самому себе. И является формой и обработчиком данных занесенных в форму. Обращаю ваше внимание, что файл сжат zip-архивом и содержит файл конфигурации config.php, дамп базы данных users, файл содержащий вспомогательные функции functions.php, файл стилей style.css и сам файл register.php. Также несколько файлов, которые отвечают за работу и генерацию символов капчи.

В этой статье вы узнаете, как создать форму регистрации и авторизации , используя HTML, JavaScript, PHP и MySql. Такие формы используются почти на каждом сайте, в независимости от его типа. Они создаются и для форума, и для интернет-магазина и для социальных сетей (такие как например Facebook, Twiter, Odnoklassniki) и для многих других типов сайтов.

Если у Вас сайт на локальном компьютере, то я надеюсь, что у Вас уже . Без него ничего работать не будет.

Создание таблицы в Базе Данных

Для того чтобы реализовать регистрацию пользователей, в первую очередь нам нужна База Данных. Если она у Вас уже есть, то замечательно, иначе, Вам нужно её создавать. В статье , я подробно объясняю, как сделать это.

И так, у нас есть База Данных (сокращённо БД), теперь нам нужно создать таблицу users в которой будем добавлять наших зарегистрированных пользователей.

Как создавать таблицу в БД, я также объяснил в статье . Перед тем как создать таблицу, нам необходимо определить какие поля она будет содержать. Эти поля будут соответствовать полям из формы регистрации.

Значит, подумали, представили какие поля будут у нашей формы и создаём таблицу users с такими полями:

  • id - Идентификатор. Поле id должно быть у каждой таблицы из БД.
  • first_name - Для сохранений имени.
  • last_name - Для сохранений фамилии.
  • email - Для сохранений почтового адреса. E-mail мы будем использовать в качестве логина, поэтому это поле должна быть уникальной, то есть иметь индекс UNIQUE.
  • email_status - Поле для указания, подтверждена ли почта или нет. Если почта подтверждена, то оно будет иметь значение 1, иначе значение 0. По умолчанию, это поле будет иметь значение 0.
  • password - Для сохранений пароля.

Все поля типа “VARCHAR” должны иметь значение по умолчанию NULL.


Если Вы хотите чтобы Ваша форма регистрации имела ещё какие-то поля, то Вы можете их здесь также добавить.

Всё, наша таблица users готова. Переходим к следующему этапу.

Подключение к Базе Данных

Базу данных мы создали, теперь необходимо к ней подключиться. Подключение будем осуществлять с помощью PHP расширения MySQLi.

В папке нашего сайта, создаём файл с именем dbconnect.php , и в нём пишем следующий скрипт:

Ошибка подключения к БД. Описание ошибки: ".mysqli_connect_error()."

"; exit(); } // Устанавливаем кодировку подключения $mysqli->set_charset("utf8"); //Для удобства, добавим здесь переменную, которая будет содержать название нашего сайта $address_site = "http://testsite.local"; ?>

Этот файл dbconnect.php нужно будет подключить к обработчикам форм.

Обратите внимание на переменную $address_site , здесь я указал название моего тестового сайта, над которым буду работать. Вы соответственно, укажите название Вашего сайта.

Структура сайта

Теперь давайте разберёмся с HTML структурой нашего сайта.

Шапку и подвал сайта вынесем в отдельные файлы, header.php и footer.php . Их будем подключать на всех страницах. А именно на главной (файл index.php ), на страницу с формой регистрации (файл form_register.php ) и на страницу с формой авторизации (файл form_auth.php ).

Блок с нашими ссылками, регистрация и авторизация , добавим в шапку сайта, чтобы они отображались на всех страницах. Одна ссылка будет ввести на страницу с формой регистрации (файл form_register.php ) а другая на страницу с формой авторизации (файл form_auth.php ).

Содержимое файла header.php:

Название нашего сайта

В итоге, главная страница, у нас выглядит так:


Конечно, у Вас на сайте может быть совсем другая структура, но это для нас сейчас не важно. Главное, чтобы присутствовали ссылки (кнопки) регистрации и авторизации.

Теперь перейдём к форме регистрации. Как Вы уже поняли, она у нас находится в файле form_register.php .

Идём в Базу Данных (в phpMyAdmin), открываем структуру таблицы users и смотрим какие поля нам нужны. Значит, нам нужны поля для ввода имени и фамилии, поле для ввода почтового адреса(Email) и поле для ввода пароля. И ещё в целях безопасности добавим поле для ввода капчи.

На сервере, в результате обработки формы регистрации, могут возникнуть различные ошибки, из-за которых пользователь не сможет зарегистрироваться. Поэтому для того чтобы пользователь понимал почему не проходит регистрация, необходимо вывести ему сообщения об этих ошибках.

Перед выводом формы добавляем блок для вывода сообщений об ошибках из сессии.

И ещё момент, если пользователь уже авторизован, и он ради интереса заходит на страницу регистрации напрямую, написав в адресную строку браузера адрес_сайта/form_register.php , то мы в этом случае вместо формы регистрации, выведем ему заголовок о том, что он уже зарегистрирован.

В общем, код файла form_register.php у нас получился таким:

Вы уже зарегистрированы

В браузере, страница с формой регистрации выглядит так:


С помощью атрибута required , мы сделали все поля обязательными к заполнению.

Обратите внимание на код формы регистрации где выводится капча :


Мы в значение атрибута src для изображения, указали путь к файлу captcha.php , который генерирует данную капчу.

Посмотрим на код файла captcha.php :

Код хорошо закомментирован, поэтому я остановлюсь только на одном моменте.

Внутри функции imageTtfText() , указан путь к шрифту verdana.ttf . Так вот для корректной работы капчи, мы должны создать папку fonts , и поместить туда файл шрифта verdana.ttf . Его Вы можете найти и скачать из интернета, или взять из архива с материалами данной статьи .

С HTML структурой мы закончили, пора двигаться дальше.

Проверка email на валидность с помощью jQuery

Любая форма нуждается в проверки на валидность введённых данных, как на стороне клиента (с помощью JavaScript, jQuery), так и на стороне сервера.

Особенную внимательность мы должны уделить полю Email. Очень важно чтобы введённый почтовый адрес был валидным.

Для данного поля input, мы задали тип email (type="email"), это нас немножко предостерегает от неправильных форматов. Но, этого недостаточно, потому что через инспектор кода, которого предоставляет нам браузер, можно легко изменить значение атрибута type с email на text , и всё, наша проверка будет уже недействительна.


И в таком случае, мы должны сделать более надёжную проверку. Для этого, воспользуемся библиотекой jQuery от JavaScript.

Для подключения библиотеки jQuery, в файле header.php между тегами , перед закрывающего тега , добавляем эту строчку:

Сразу после этой строчки, добавим код проверки валидации email. Здесь же добавим код проверки длины введённого пароля. Его длина должна быть не меньше 6 символов.

С помощью данного скрипта, мы проверяем введённого почтового адреса на валидность. Если пользователь ввёл неправильный Email, то мы выводим ему ошибку об этом и дезактивируем кнопку отправки формы. Если всё хорошо, то мы убираем ошибку и активируем кнопку отправки формы.

И так, с проверкой формы на клиентской части мы закончили. Теперь мы можем отправить её на сервер, где также сделаем пару проверок и добавим данные в БД.

Регистрация пользователя

Форму мы отправляем на обработку файлу register.php , через метод POST. Название данного файла обработчика, указано в значение атрибута action . А метод отправки указано в значение атрибута method .

Открываем этот файл register.php и первое что нам нужно сделать, это написать функцию запуска сессии и подключить созданный нами ранее файл dbconnect.php (В этом файле мы сделали подключение к БД). И ещё, сразу объявим ячейки error_messages и success_messages в глобальном массиве сессии. В error_mesages будем записывать все сообщения об ошибках возникающие при обработке формы, а в succes_messages , будем записывать радостные сообщения.

Перед тем как продолжить, мы должны проверить, была ли вообще отправлена форма . Злоумышленник, может посмотреть на значение атрибута action из формы, и узнать какой файл занимается обработкой данной формы. И ему может прийти в голову мысль перейти напрямую в этот файл, набирая в адресной строке браузера такой адрес: http://арес_сайта/register.php

Поэтому нам нужно проверить наличие ячейки в глобальном массиве POST, имя которой соответствует имени нашей кнопки "Зарегистрироваться" из формы. Таким образом мы проверяем была ли нажата кнопка "Зарегистрироваться" или нет.

Если злоумышленник попытается перейти напрямую в этот файл, то он получить сообщение об ошибке. Напоминаю, что переменная $address_site содержит название сайта и оно было объявлено в файле dbconnect.php .

Ошибка! главную страницу .

"); } ?>

Значение капчи в сессии было добавлено при её генерации, в файле captcha.php . Для напоминания покажу ещё раз этот кусок кода из файла captcha.php , где добавляется значение капчи в сессию:

Теперь приступим к самой проверке. В файле register.php , внутри блока if, где проверяем была ли нажата кнопка "Зарегистрироваться", а точнее где указан комментарий " // (1) Место для следующего куска кода " пишем:

//Проверяем полученную капчу //Обрезаем пробелы с начала и с конца строки $captcha = trim($_POST["captcha"]); if(isset($_POST["captcha"]) && !empty($captcha)){ //Сравниваем полученное значение с значением из сессии. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){ // Если капча не верна, то возвращаем пользователя на страницу регистрации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу. $error_message = "

Ошибка! Вы ввели неправильную капчу

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (2) Место для следующего куска кода }else{ //Если капча не передана либо оно является пустой exit("

Ошибка! Отсутствует проверечный код, то есть код капчи. Вы можете перейти на главную страницу .

"); }

Далее, нам нужно обрабатывать полученные данные, из массива POST. Первым делом, нам нужно проверить содержимое глобального массива POST, то есть находится ли там ячейки, имена которых соответствуют именам полей input из нашей формы.

Если ячейка существует, то обрезаем пробелы с начала и с конца строки из этой ячейки, иначе, перенаправляем пользователя обратно на страницу с формой регистрации.

Далее, после того как обрезали пробелы, добавляем строку в переменную и проверяем эту переменную на пустоту, если она не является пустой, то идём дальше, иначе перенаправляем пользователя обратно на страницу с формой регистрации.

Этот код вставляем в указанное место "// (2) Место для следующего куска кода ".

/* Проверяем если в глобальном массиве $_POST существуют данные отправленные из формы и заключаем переданные данные в обычные переменные.*/ if(isset($_POST["first_name"])){ //Обрезаем пробелы с начала и с конца строки $first_name = trim($_POST["first_name"]); //Проверяем переменную на пустоту if(!empty($first_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $first_name = htmlspecialchars($first_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваше имя

Отсутствует поле с именем

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["last_name"])){ //Обрезаем пробелы с начала и с конца строки $last_name = trim($_POST["last_name"]); if(!empty($last_name)){ // Для безопасности, преобразуем специальные символы в HTML-сущности $last_name = htmlspecialchars($last_name, ENT_QUOTES); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Вашу фамилию

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле с фамилией

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["email"])){ //Обрезаем пробелы с начала и с конца строки $email = trim($_POST["email"]); if(!empty($email)){ $email = htmlspecialchars($email, ENT_QUOTES); // (3) Место кода для проверки формата почтового адреса и его уникальности }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } if(isset($_POST["password"])){ //Обрезаем пробелы с начала и с конца строки $password = trim($_POST["password"]); if(!empty($password)){ $password = htmlspecialchars($password, ENT_QUOTES); //Шифруем папроль $password = md5($password."top_secret"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш пароль

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } // (4) Место для кода добавления пользователя в БД

Особенную важность имеет поле email . Мы должны проверить формат полученного почтового адреса и его уникальность в БД. То есть не зарегистрирован ли уже какой-то пользователь с таким же почтовым адресом.

В указанном месте "// (3) Место кода для проверки формата почтового адреса и его уникальности " добавляем следующий код:

//Проверяем формат полученного почтового адреса с помощью регулярного выражения $reg_email = "/^**@(+(*+)*\.)++/i"; //Если формат полученного почтового адреса не соответствует регулярному выражению if(!preg_match($reg_email, $email)){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Вы ввели неправельный email

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } //Проверяем нет ли уже такого адреса в БД. $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`="".$email."""); //Если кол-во полученных строк ровно единице, значит пользователь с таким почтовым адресом уже зарегистрирован if($result_query->num_rows == 1){ //Если полученный результат не равен false if(($row = $result_query->fetch_assoc()) != false){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Пользователь с таким почтовым адресом уже зарегистрирован

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка в запросе к БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); } /* закрытие выборки */ $result_query->close(); //Останавливаем скрипт exit(); } /* закрытие выборки */ $result_query->close();

И так, мы закончили со всеми проверками, пора добавить пользователя в БД. В указанном месте " // (4) Место для кода добавления пользователя в БД " добавляем следующий код:

//Запрос на добавления пользователя в БД $result_query_insert = $mysqli->query("INSERT INTO `users` (first_name, last_name, email, password) VALUES ("".$first_name."", "".$last_name."", "".$email."", "".$password."")"); if(!$result_query_insert){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка запроса на добавления пользователя в БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); }else{ $_SESSION["success_messages"] = "

Регистрация прошла успешно!!!
Теперь Вы можете авторизоваться используя Ваш логин и пароль.

"; //Отправляем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); } /* Завершение запроса */ $result_query_insert->close(); //Закрываем подключение к БД $mysqli->close();

Если в запросе на добавления пользователя в БД произошла ошибка, мы добавляем сообщение об этой ошибке в сессию и возвращаем пользователя на страницу регистрации.

Иначе, если все прошло хорошо, в сессию мы также добавляем сообщение, но уже более приятна, а именно говорим пользователю что регистрация прошла успешно. И перенаправляем его уже на страницу с формой авторизации.

Скрипт для проверки формата почтового адреса и длины пароля находится в файле header.php , поэтому он будет действовать и на поля из этой формы.

Запуск сессии также происходит в файле header.php , поэтому в файле form_auth.php сессию запускать не нужно, потому что получим ошибку.


Как я уже сказал, скрипт проверки формата почтового адреса и длины пароля здесь также действует. Поэтому если пользователь введёт неправильный почтовый адрес или короткий пароль, то он сразу же получить сообщение об ошибке. А кнопка войти станет не активной.

После устранения ошибок кнопка войти становится активной, и пользователь сможет отправить форму на сервер, где она будет обрабатываться.

Авторизация пользователя

В значение атрибута action у форы авторизации указан файл auth.php , это значит, что форма будет обрабатываться именно в этом файле.

И так, открываем файл auth.php и пишем код для обработки формы авторизации. Первое что нужно сделать это запустить сессию и подключить файл dbconnect.php для соединения с БД.

//Объявляем ячейку для добавления ошибок, которые могут возникнуть при обработке формы. $_SESSION["error_messages"] = ""; //Объявляем ячейку для добавления успешных сообщений $_SESSION["success_messages"] = "";

/* Проверяем была ли отправлена форма, то есть была ли нажата кнопка Войти. Если да, то идём дальше, если нет, то выведем пользователю сообщение об ошибке, о том что он зашёл на эту страницу напрямую. */ if(isset($_POST["btn_submit_auth"]) && !empty($_POST["btn_submit_auth"])){ //(1) Место для следующего куска кода }else{ exit("

Ошибка! Вы зашли на эту страницу напрямую, поэтому нет данных для обработки. Вы можете перейти на главную страницу .

"); }

//Проверяем полученную капчу if(isset($_POST["captcha"])){ //Обрезаем пробелы с начала и с конца строки $captcha = trim($_POST["captcha"]); if(!empty($captcha)){ //Сравниваем полученное значение с значением из сессии. if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){ // Если капча не верна, то возвращаем пользователя на страницу авторизации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу. $error_message = "

Ошибка! Вы ввели неправильную капчу

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ $error_message = "

Ошибка! Поле для ввода капчи не должна быть пустой.

"; // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] = $error_message; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } //(2) Место для обработки почтового адреса //(3) Место для обработки пароля //(4) Место для составления запроса к БД }else{ //Если капча не передана exit("

Ошибка! Отсутствует проверочный код, то есть код капчи. Вы можете перейти на главную страницу .

"); }

Если пользователь ввёл проверочный код правильно, то идём дальше, иначе возвращаем его на страницу авторизации.

Проверка почтового адреса

//Обрезаем пробелы с начала и с конца строки $email = trim($_POST["email"]); if(isset($_POST["email"])){ if(!empty($email)){ $email = htmlspecialchars($email, ENT_QUOTES); //Проверяем формат полученного почтового адреса с помощью регулярного выражения $reg_email = "/^**@(+(*+)*\.)++/i"; //Если формат полученного почтового адреса не соответствует регулярному выражению if(!preg_match($reg_email, $email)){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Вы ввели неправильный email

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Поле для ввода почтового адреса(email) не должна быть пустой.

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_register.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле для ввода Email

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } //(3) Место для обработки пароля

Если пользователь ввёл почтовый адрес в неправильном формате или значение поля почтового адреса является пустой, то мы возвращаем его на страницу авторизации где выводим ему сообщение об этом.

Проверка пароля

Следующее поле для обработки, это поле с паролем. В указанное место "//(3) Место для обработки пароля ", пишем:

If(isset($_POST["password"])){ //Обрезаем пробелы с начала и с конца строки $password = trim($_POST["password"]); if(!empty($password)){ $password = htmlspecialchars($password, ENT_QUOTES); //Шифруем пароль $password = md5($password."top_secret"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Укажите Ваш пароль

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Отсутствует поле для ввода пароля

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); }

Здесь мы с помощью функции md5() шифруем полученный пароль, так как в БД пароли у нас находятся именно в зашифрованном виде. Дополнительное секретное слово в шифровании, в нашем случае "top_secret " должна быть та которая использовалась и при регистрации пользователя.

Теперь необходимо сделать запрос к БД на выборке пользователя у которого почтовый адрес равен полученному почтовому адресу и пароль равен полученному паролю.

//Запрос в БД на выборке пользователя. $result_query_select = $mysqli->query("SELECT * FROM `users` WHERE email = "".$email."" AND password = "".$password."""); if(!$result_query_select){ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Ошибка запроса на выборке пользователя из БД

"; //Возвращаем пользователя на страницу регистрации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); }else{ //Проверяем, если в базе нет пользователя с такими данными, то выводим сообщение об ошибке if($result_query_select->num_rows == 1){ // Если введенные данные совпадают с данными из базы, то сохраняем логин и пароль в массив сессий. $_SESSION["email"] = $email; $_SESSION["password"] = $password; //Возвращаем пользователя на главную страницу header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/index.php"); }else{ // Сохраняем в сессию сообщение об ошибке. $_SESSION["error_messages"] .= "

Неправильный логин и/или пароль

"; //Возвращаем пользователя на страницу авторизации header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$address_site."/form_auth.php"); //Останавливаем скрипт exit(); } }

Выход с сайта

И последнее что мы реализуем, это процедура выхода с сайта . На данный момент в шапке у нас выводятся ссылки на страницу авторизации и на страницу регистрации.

В шапке сайта (файл header.php ), с помощью сессии мы проверяем, авторизован ли уже пользователь. Если нет, то выводим ссылки регистрации и авторизации, в противном случае (если он авторизован) то вместо ссылок регистрации и авторизации выводим ссылку Выход .

Модифицированный кусок кода из файла header.php :

Регистрация

Выход

При нажатии на ссылку выхода с сайта, мы попадаем в файл logout.php , где просто уничтожаем ячейки с почтовым адресом и паролем из сессии. После этого возвращаем пользователя обратно на ту страницу, на которой была нажата ссылка выход .

Код файла logout.php:

На этом всё. Теперь Вы знаете как реализовать и обрабатывать формы регистрации и авторизации пользователя на своём сайте. Эти формы встречаются почти на каждом сайте, поэтому каждый программист должен знать, как их создавать.

Ещё мы научились проверять вводимые данные, как на стороне клиента (в браузере, с помощью JavaScript, jQuery) так и на стороне сервера (с помощью языка PHP). Также мы научились реализовать процедуру выхода с сайта .

Все скрипты проверены и рабочие. Архив с файлами этого маленького сайта Вы можете скачать по этой ссылке .

В будущем я напишу статью где опишу . И ещё планирую написать статью где объясню, (без перезагрузки страницы). Так что, для того чтобы быть в курсе о выходе новых статей можете подписаться на мой сайт.

При возникновении вопросов обращайтесь, также, если вы заметили, какую-то ошибку в статье прошу вас, сообщите, мне об этом.

План урока (Часть 5):

  1. Создаем HTML структуру для формы авторизации
  2. Обрабатываем полученные данные
  3. Выводим приветствие пользователя в шапку сайта

Понравилась статья?

What is Form?

When you login into a website or into your mail box, you are interacting with a form.

Forms are used to get input from the user and submit it to the web server for processing.

The diagram below illustrates the form handling process.

A form is an HTML tag that contains graphical user interface items such as input box, check boxes radio buttons etc.

The form is defined using the

...
tags and GUI items are defined using form elements such as input.

In this tutorial, you will learn-

When and why we are using forms?

  • Forms come in handy when developing flexible and dynamic applications that accept user input.
  • Forms can be used to edit already existing data from the database

Create a form

We will use HTML tags to create a form. Below is the minimal list of things you need to create a form.

  • Opening and closing form tags
  • Form submission type POST or GET
  • Submission URL that will process the submitted data
  • Input fields such as input boxes, text areas, buttons,checkboxes etc.

The code below creates a simple registration form

Registration Form

Registration Form

First name:
Last name:

Viewing the above code in a web browser displays the following form.


  • … are the opening and closing form tags
  • action="registration_form.php" method="POST"> specifies the destination URL and the submission type.
  • First/Last name: are labels for the input boxes
  • are input box tags

  • is the new line tag
  • is a hidden value that is used to check whether the form has been submitted or not
  • is the button that when clicked submits the form to the server for processing

Submitting the form data to the server

The action attribute of the form specifies the submission URL that processes the data. The method attribute specifies the submission type.

PHP POST method

  • This is the built in PHP super global array variable that is used to get values submitted via HTTP POST method.
  • This method is ideal when you do not want to display the form post values in the URL.
  • A good example of using post method is when submitting login details to the server.

It has the following syntax.

  • “$_POST[…]” is the PHP array

PHP GET method

  • This is the built in PHP super global array variable that is used to get values submitted via HTTP GET method.
  • The array variable can be accessed from any script in the program; it has a global scope.
  • This method displays the form values in the URL.
  • It’s ideal for search engine forms as it allows the users to book mark the results.

It has the following syntax.

  • “$_GET[…]” is the PHP array
  • “"variable_name"” is the URL variable name.

GET vs POST Methods

POST GET
Values not visible in the URL Values visible in the URL
Has not limitation of the length of the values since they are submitted via the body of HTTP Has limitation on the length of the values usually 255 characters. This is because the values are displayed in the URL. Note the upper limit of the characters is dependent on the browser.
Has lower performance compared to Php_GET method due to time spent encapsulation the Php_POST values in the HTTP body Has high performance compared to POST method dues to the simple nature of appending the values in the URL.
Supports many different data types such as string, numeric, binary etc. Supports only string data types because the values are displayed in the URL
Results cannot be book marked Results can be book marked due to the visibility of the values in the URL

The below diagram shows the difference between get and post



Processing the registration form data

The registration form submits data to itself as specified in the action attribute of the form.

When a form has been submitted, the values are populated in the $_POST super global array.

We will use the PHP isset function to check if the form values have been filled in the $_POST array and process the data.

We will modify the registration form to include the PHP code that processes the data. Below is the modified code

Registration Form //this code is executed when the form is submitted

Thank You

You have been registered as

Go back to the form

Registration Form

First name:
Last name:

  • checks if the form_submitted hidden field has been filled in the $_POST array and display a thank you and first name message.

    If the form_fobmitted field hasn’t been filled in the $_POST array, the form is displayed.

More examples

Simple search engine

We will design a simple search engine that uses the PHP_GET method as the form submission type.

For simplicity’s sake, we will use a PHP If statement to determine the output.

We will use the same HTML code for the registration form above and make minimal modifications to it.

Simple Search Engine

Search Results For

The GET method displays its values in the URL

Sorry, no matches found for your search term

Go back to the form

Simple Search Engine - Type in GET

Search Term:

View the above page in a web browser

The following form will be shown

Type GET in upper case letter then click on submit button.

The following will be shown

The diagram below shows the URL for the above results

Note the URL has displayed the value of search_term and form_submitted. Try to enter anything different from GET then click on submit button and see what results you will get.

Working with check boxes, radio buttons

If the user does not select a check box or radio button, no value is submitted, if the user selects a check box or radio button, the value one (1) or true is submitted.

We will modify the registration form code and include a check button that allows the user to agree to the terms of service.

Registration Form

You have not accepted our terms of service

Thank You

You have been registered as

Go back to the form

Registration Form

First name:
Last name:
Agree to Terms of Service:

View the above form in a browser