Создание и проверка форм. Создание простой системы регистрации пользователей на PHP и MySQL Аристократия register form php
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
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
Thank You
You have been registered as
Go back to the form
Registration Form
- 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.
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
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.
You have not accepted our terms of service
Thank You
You have been registered as
Go back to the form
Registration Form
View the above form in a browser
I am glad to post here my knowledge and techniques used in PHP and MySQL. As you all aware that PHP and MySQL are the most widely used Open Source for websites. Today’s millions of websites and applications are using these free software’s. Personally I feel that this could be next level for front end developers by using PHP and MySQL a HTML developer can make a website more dynamic. Let us discuss How to create a Basic registration form in PHP with database, Its simple and very useful for a basic website dynamic user dynamic registration. Every creative can implement its basic structure to their website. Now Just follow these simple steps and you will find that your first dynamic functional registration form with database entry on every form fill up.
STEP 1: Create Database for inserting values
Go to MySQL, Create database student; Qurey OK, 1 row affected (0.00 sec) mysql> use student Database changed mysql> create table student(id int,name varchar(40),email varchar(80),password varchar(40)); Query OK, 0 rows affected (0.05 sec)STEP 2: Front end code, Make HTML Structure of your registration form
Make a new file registration.html we will make it in PHP later, the structure would be:STEP 3: For Database connectivity using MySQL
Create a connect.php file for basic database connection use that default code as belowSTEP 4: Finally create a registration.php page to get value of all fields shown in HTML page
Here a Front end developer can write some own code in PHP, Read the code and understand this basic structure line by line you will find it very easy.Conclusion
By following step by step procedure provided above a basic registration form can be created. So best of luck for your first PHP code Get the codeLaravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it"s a dependency management tool for php similar to node"s npm.
To install Composer on your machine, check this post:
Installing Laravel on Windows:
Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".
STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".
STEP-2) Enter the following command.
Composer create-project laravel/laravel my_laravel_site --prefer-dist
Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.
STEP-3) Now it"s time to be patient as laravel installation is going to take some time.
STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.
Php artisan serve
STEP-5) This will show a message something like, "Laravel development server started:" along with an url.
STEP-6) Copy and paste the url on the browser. If things go right, you"d see the laravel welcome screen.
STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.
Setting Application Key:
Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.
In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.
Php artisan key:generate
Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.
Installing Specific Laravel Version:
The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.
Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:
Likewise you can easily install laravel using composer on windows . I hope you find this tutorial useful. Please share it on your social circle if you like it.
Формы - непременная часть любого вёб-приложения. Мы используем их для авторизации и регистрации нового пользователя, на странице обратной связи, при отправки комментария и для множества других задач. Однако их создание и последующая проверка может быть неприятным процессом - и здесь на сцену выходит Laravel, который даёт нам несколько аккуратных классов для интуитивно понятной работы с формами и их данными.
Создание форм в Laravel
Создавать формы в Laravel неожиданно просто. По большей части ничего не мешает вам использовать стандартные теги HTML, но Laravel может значитель облегчить вам жизнь. Скажем, класс PHP Form имеет метод PHP label () , позволяющий вам связать метки с полями формы используя соответствующие (автосгенерированные) ID. Давайте в качестве примера создадим простую форму:
PHP
Register!
?>
Всё очевидно, не так ли? Мы открываем форму POST -запроса на маршруте register , создаём несколько меток и полей ввода и добавляем CSRF-ключ, после чего закрываем форму. Если нам нужен безопасный маршрут (с использованием HTTPS ), то заменим вызов PHP Form :: open () на вызов PHP Form :: open_secure () , а если нам нужно создать форму для загрузки файлов, то пригодится PHP Form :: open_for_files () .
Вы наверняка заметили некие вызовы PHP Input :: old () - о них мы поговорим , а пока просто запомните, что они здесь есть.
Класс Form содержит множество методов для простого создания форм - вы можете ознакомиться с ними в документации .
Подделка межсайтовых запросов (CSRF)
Я не буду вдаваться в подробности о CSRF - Jeff Atwood написал очень наглядную статью о том, что это такое и как этого избежать.
Метод Form::token() создаёт случайную последовательность символов, сохраняет её в данных сессии (это значит, что вам нужно включить их поддержку в application/config/session.php) и выводит её в виде скрытого поля формы. При обработке запроса от формы, использующей CSRF-ключ мы можем использовать встроенный фильтр csrf для проверки того, что никто не «поработал» над запросом и он действительно исходит от пользователя.
Вот как выглядит код фильтра (файл application/routes.php ):
PHP
Route
::
filter
("csrf"
, function () {
if (Request
::
forged
()) return
Response
::
error
("500"
);
});
Мы можем настроить его как нам нужно, но для этой статьи нам вполне хватит стандартного обработчика.
PHP
Route
::
post
("register"
, array("before"
=>
"csrf"
, function () {
// регистрация нового пользователя.
}));
Вот и всё, что нам нужно для включения CSRF-фильтра - просто убедится, что он указан в списке before .
Проверка введённых данных
Теперь, когда мы удостоверились, что пришедшему запросу можно доверять, нам нужно проверить данные, которые ввёл в форму пользователь. Вернёмся к нашему марштуру register , добавим туда проверку, а затем я объясню, что к чему.
Несколько человек заметили, что проверка не должна выполняться в контроллере. Обычно лучше всего делать это в модели - моя следующая статья «Продвинутая проверка ввода в Laravel » описывает именно этот способ решения задачи.
PHP // файл application/routes.php.
Route
::
post
("register"
, array("before"
=>
"csrf"
, function () {
$rules
= array(
"username"
=> array("required"
,
"unique:users,username"
),
"email"
=> array("required"
,
"email"
,
"unique:users,email"
),
"password"
=> array("required"
,
"min:7"
)
);
$validation = Validator :: make (Input :: all (), $rules );
If ($validation
->
fails
()) {
// проверка не пройдена.
return
Redirect
::
to
("register"
)->
with_input
()->
with_errors
($validation
);
}
// данные прошли проверку - можем создавать нового пользователя.
}));
- Определяем массив правил - ключи соответствуют именам полей ввода формы, значения - правилам, которым они должны соответствовать. В нашем случае поле username («имя пользователя» ) должно быть заполнено (required) и уникально (unique).
- Создаём объект PHP Validator - первым параметром он принимает данные для проверки (в нашем случае данные формы, полученные через POST ), вторым - набор правил.
- Затем мы выполняем проверку - если она не прошла, переадресуем пользователя обратно к маршруту register (используя GET ) со старым вводом и сообщениями об ошибках.
- Если же все поля заполнены верно - регистрируем новую учётную запись, авторизуем пользователя, либо делаем что-то ещё.
Последовательность действий, которые мы здесь выполняем, называют шаблоном «Post/Redirect/Get » (PRG) - это отличный способ предотвратить двойную отправку формы.
Теперь посмотрим на правила, которые мы определили выше.
required - обозначает, что поле должно быть заполнено - иными словами, оно должно иметь значение.
unique - здесь немного более сложный момент. Это правило принимает 3 параметра, 2 из которых можно опустить. Первый параметр - имя таблицы, в котором нужно проверять значение на уникальность; второй - имя поля в таблице, если оно не соответствует имени поля в форме (в этом случае его можно пропустить); третий и последний параметр - значение (id ) для первичного ключа.
Предположим, что мы обновляем существующий профиль пользователя - мы точно так же хотим, чтобы его e-mail был уникальным, но если он решил не изменять свой адрес, то нам не стоит говорить, что введённый e-mail уже занят - им самим. Для этого мы и передаём ID пользователя - Laravel исключит соответствующую запись из проверки.
PHP
$rules
= array(
"email"
=> array("required"
,
"email"
,
"unique:users,email,"
.
$user
->
id
)
);
e-mail - проверяет, что введённое значение похоже на правильный e-mail адрес, но не проверяет его на существование .
min - устанавливает минимально допустимую длину значения данного поля.
Полный список доступных правил можно найти в документации .
Отображение ошибок
Свойство PHP $validation -> errors содержит тот же объект Messages со всеми ошибками, найденными во входных данных. Laravel определит, что была выполнена переадресация с ошибками и автоматически привяжет этот объект к представлению . Вы скоро поймёте, что я имею в виду.
Помните вызовы PHP Input :: old () в ? Когда мы переадресовываем запрос со вводом они вернут значения, которые пользователь ввёл в форму ранее. Поэтому если я сказал, что моё имя - «Jason» , но регистрация не произошла, «Jason» останется введённым даже после переадресации меня обратно на форму. Отлично!
Поля ввода паролей изначально не имеют значения по умолчанию, но вы можете задать его явно используя массив атрибутов :
PHP echo Form :: password ("password" , array("value" => Input :: old ("password" )));
Вернёмся к нашей форме. Как вы помните, у нас есть переменная $errors - объект PHP Messages . Давайте сделаем нашу форму более дружелюбной, отображая ошибки, когда она была неверно заполнена:
PHP
Register!
Echo Form :: open ("register" , "POST" );
echo Form :: label ("username" , "Username" ) . Form :: text ("username" , Input :: old ("username" ));
if ($errors
->
has
("username"
)) {
echo
$errors
->
first
("username"
);
}
echo Form :: label ("email" , "E-mail" ) . Form :: text ("email" , Input :: old ("email" ));
if ($errors
->
has
("email"
)) {
echo
$errors
->
first
("email"
);
}
echo Form :: label ("password" , "Password" ) . Form :: password ("password" );
if ($errors
->
has
("password"
)) {
echo
$errors
->
first
("password"
);
}
echo Form :: submit ("Register!" );
echo Form :: token () . Form :: close ();
?>
Сообщения будут показаны только в случае, когда определённое поле содержит ошибки.
Вы можете отформатировать сообщение в нужный HTML передав его во втором параметре:
PHP echo $errors -> first ("username" , ":message" );
Либо, если вы хотите отобразить первое сообщение об ошибке для любого поля, а не только для username
: ));
?>
PHP $errors -> all () возвращает массив отформатированных сообщений, поэтому мы объединяем его в строку.
Собственные правила и ошибки
Часто вам понадобится создавать собственные правила для проверки ввода. До Laravel 3 это делалось наследованием класса Validator и добавлением к нему методов. С поддержкой пакетов потребовалось более надёжное решение, чтобы не создавать множество подклассов. Laravel 3 позволяет регистрировать произвольные правила с помощью PHP Validator :: register () :
PHP
// этот код может быть помещён, например, в application/start.php:
Validator
::
register
("starts_with"
, function ($attribute
,
$value
,
$parameters
) {
return
starts_with
($value
,
$parameters
[
0
]);
});
В этом простом обработчике мы просто возвращаем true , если значение начинается на указанную строку (переданную в первом и единственном параметре), и false в противном случае. Здесь используется одна из немногих глобальных функций Laravel - PHP starts_with () .
Использование нового правила:
PHP
$rules
= array(
"website"
=> array("required"
,
"starts_with:http://"
)
);
Здесь нам потребовалось определить поле как обязательное («required» ). Крмое этого нам также нужно добавить сообщение об ошибке в файл application/language/en/validation.php :
PHP
"custom"
=> array(
"website_starts_with"
=>
"Website must start with http://"
)
Либо можно это сделать при создании экземпляра Validator , передав его в третьем параметре :
Итак, мы с вами создали форму, отправляющую POST -запрос на наш маршрут , где происходит проверка ввода контроллером - который, в свою очередь, при обнаружении ошибок отправляет клиента обратно с сохранением предыдущего ввода и выводом соответствующих сообщений.
PHP | 25 Jan, 2017 | Clever TechieIn 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.