Программы. Советы. Безопасность. Интересное. Накопитель

PHP сценарии обработки HTML форм. Создание простой системы регистрации пользователей на PHP и MySQL Кладь registration form php

У Вас в браузере заблокирован JavaScript. Разрешите JavaScript для работы сайта!

Работа с формами

Для передачи данных от пользователя Web-страницы на сервер используются HTML-формы. Для работы с формами в PHP предусмотрен ряд специальных средств.

Предварительно определенные переменные

В PHP существует ряд предварительно определенных переменных, которые не меняются при выполнении всех приложений в конкретной среде. Их также называют переменными окружения или переменными среды. Они отражают установки среды Web-сервера Apache, а также информацию о запросе данного браузера. Есть возможность получить значения URL, строки запроса и других элементов HTTP-запроса.

Все предварительно определенные переменные содержатся в ассоциативном массиве $GLOBALS . Кроме переменных окружения этот массив содержит также глобальные переменные, определенные в программе.

Пример 1

Просмотр массива $GLOBALS $value) echo "\$GLOBALS[\"$key\"] == $value
"; ?>

В результате на экране появится список всех глобальных переменных, включая переменные окружения. Наиболее часто используемые из них:

Переменная Описание Cодержание
$_SERVER["HTTP_USER_AGENT"] Название и версия клиента Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
$_SERVER["REMOTE_ADDR"] IP-адрес 144.76.78.4
getenv("HTTP_X_FORWARDED_FOR") Внутренний IP-адрес клиента
$_SERVER["REQUEST_METHOD"] Метод запроса (GET или POST ) GET
$_SERVER["QUERY_STRING"] При запросе GET закодированные данные, передаваемые вместе с URL
$_SERVER["REQUEST_URL"] Полный адрес клиента, включая строку запроса
$_SERVER["HTTP_REFERER"] Адрес страницы, с которой был сделан запрос
$_SERVER["PHP_SELF"] Путь к выполняемой программе /index.php
$_SERVER["SERVER_NAME"] Домен сайт
$_SERVER["REQUEST_URI"] Путь /php/php_form.php

Обработка ввода пользователя

PHP-программу обработки ввода можно отделить от HTML-текста, содержащего формы ввода, а можно расположить на одной странице.

Пример 2

Пример обработки ввода

" method="post">

Номер карточки:

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

При обработки элемента с многозначным выбором для доступа ко всем выбранным значениям нужно к имени элемента добавить пару квадратных скобок. Для выбора нескольких эллементов следует удерживать клавишу Ctrl.

Пример 3.1

Список

РЕЗУЛЬТАТ ПРИМЕРА 3.1:

Пример 3.2

Обработка списка из файла ex1.htm

    "; foreach ($Item as $value) echo "
  • $value"; echo "
"; ?>

Пример 4. Прием значений от checkbox-флажков

$v) { if($v) echo "Вы знаете язык программирования $k!
"; else echo "Вы не знаете языка программирования $k.
"; } } ?>
" method="post"> Какие языки программирования вы знаете?
PHP
Perl

РЕЗУЛЬТАТ ПРИМЕРА 4:

Пример 5

"; ?>
" method="post">

Можно обрабатывать формы, не заботясь о фактических именах полей.

Для этого можно использовать (в зависимости от метода передачи) ассоциативный массив $HTTP_GET_VARS или $HTTP_POST_VARS . Эти массивы содержат пары имя/значение для каждого элемента переданной формы. Если Вам все равно, Вы можете использовать ассоциативный массив $_REQUEST .

Пример 6

Обработка произвольного ввода независимо от метода передачи $value) echo "$key == $value
"; ?>

Пример 7. Обработка нажатия на кнопку с использованием оператора "@".

">

С помощью функции header() , послав браузеру заголовок "Location" , можно перенаправить пользователя на новую страницу.

Например:

Передача файла на сервер. Залить файл. UpLoad

PHP позволяет передавать на сервер файлы. HTML-форма, предназначенная для передачи файла, должна содержать аргумент enctype="multipart/form-data" .

Кроме того в форме перед полем для копирования файла должно находиться скрытое поле с именем max_file_size . В это скрытое поле должен быть записан максимальный размер передаваемого файла (обычно не больше 2 Мбайт).

Само поле для передачи файла - обычный элемент INPUT с аргументом type="file" .

Например:

" method="post">

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

Пример 8

Обработка переданного файла "; echo "имя: ".$_FILES["userfile"]["name"]."
"; echo "размер: ".$_FILES["userfile"]["size"]."
"; echo "тип: ".$_FILES["userfile"]["type"]."
"; } ?>
" method="post">

Примеры загрузки файлов на сервер

Если возникнут проблеммы с перекодировкой сервером загруженного файла, символ с кодом 0х00 заменен на пробел (символ с кодом 0х20 ), допишите в файл httpd.conf из каталога Апача (/usr/local/apache) следующие строки.

CharsetRecodeMultipartForms Off

Laravel 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.

Last modified on July 23rd, 2019 by Vincy.

User registration or sign up is an integral part of many web applications and it is critical to get it right for the success of the application. It is the starting point of user engagement with your application.

It should be as simple as possible with best UI / UX. Implementing user registration functionality using PHP is a simple task and I will walk you through the steps with example in this article.

What is inside?

How this PHP user registration example works?

This example code can be separated into 3 parts.

  1. Getting user information via a HTML form.
  2. Validating user submitted information on form submit.
  3. Database handling to save registered user to the database after validation.

The third step will be executed after ensuring that the user is not added already. This data uniqueness validation will be performed based on their email and username entered by them.

During registration we generally collect user information, who are ready to register with our application. Some of them will be mandatory and some of them will be optional.

So, this functionality may also include validation part to ensure about the non-emptiness and the format of the user data. The validation could be done either in client-side or server side.

Having validation at server-side is always better. You can choose to have it in client-side also for the ease of use of the users. But having at the server-side is not optional and a minimum requirement.

File structure

HTML form to allow user to register

In this example, the registration form contains the fields Username, Name(Display Name), Password and Email. It also has the Confirm Password field to let the user to reenter his password for the confirmation. These two passwords will be compared later at the time of a .

By submitting this form, the user is expected to agree the terms and conditions. So a checkbox field is added before the Register button for ensuring it.

PHP User Registration Form

Sign Up
"; } ?>
">
">
">
I accept terms and conditions

And the styles are,

Body { font-family: Arial; color: #333; font-size: 0.95em; } .form-head { color: #191919; font-weight: normal; font-weight: 400; margin: 0; text-align: center; font-size: 1.8em; } .error-message { padding: 7px 10px; background: #fff1f2; border: #ffd5da 1px solid; color: #d6001c; border-radius: 4px; margin: 30px 0px 10px 0px; } .success-message { padding: 7px 10px; background: #cae0c4; border: #c3d0b5 1px solid; color: #027506; border-radius: 4px; margin: 30px 0px 10px 0px; } .demo-table { background: #ffffff; border-spacing: initial; margin: 15px auto; word-break: break-word; table-layout: auto; line-height: 1.8em; color: #333; border-radius: 4px; padding: 20px 40px; width: 380px; border: 1px solid; border-color: #e5e6e9 #dfe0e4 #d0d1d5; } .demo-table .label { color: #888888; } .demo-table .field-column { padding: 15px 0px; } .demo-input-box { padding: 13px; border: #CCC 1px solid; border-radius: 4px; width: 100%; } .btnRegister { padding: 13px; background-color: #5d9cec; color: #f5f7fa; cursor: pointer; border-radius: 4px; width: 100%; border: #5791da 1px solid; font-size: 1.1em; } .response-text { max-width: 380px; font-size: 1.5em; text-align: center; background: #fff3de; padding: 42px; border-radius: 3px; border: #f5e9d4 1px solid; font-family: arial; line-height: 34px; margin: 15px auto; } .terms { margin-bottom: 5px; }

How to validate user information on form submit

A server-side form validation script is added in this example for validating the user registration data. This PHP validation script will be called on submitting the registration form.

This script validates all form fields to check the non-emptiness for each field. Then it validates the user email format using PHP filter_var() function.

As the registration includes password confirmation feature, the password comparison will take place at this part of this example.

Finally, the validation script will check if the user accepts term and condition by checking the appropriate box on the form.

Once all the validation completed by returning boolean true, then the actual registration process will take place.

Function validateMember() { $valid = true; $errorMessage = array(); foreach ($_POST as $key => $value) { if (empty($_POST[$key])) { $valid = false; } } if($valid == true) { if ($_POST["password"] != $_POST["confirm_password"]) { $errorMessage = "Passwords should be same."; $valid = false; } if (! isset($error_message)) { if (! filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) { $errorMessage = "Invalid email address."; $valid = false; } } if (! isset($error_message)) { if (! isset($_POST["terms"])) { $errorMessage = "Accept terms and conditions."; $valid = false; } } } else { $errorMessage = "All fields are required."; } if ($valid == false) { return $errorMessage; } return; }

PHP MySQL code to access database to save registered user

Server-side user form validation

This is the PHP entry point to handle all the server-side script to validate form and to handle database operations based on the validation result.

validateMember($username, $displayName, $password, $email); if (empty($errorMessage)) { $memberCount = $member->isMemberExists($username, $email); if ($memberCount == 0) { $insertId = $member->insertMemberRecord($username, $displayName, $password, $email); if (! empty($insertId)) { header("Location: thankyou.php"); } } else { $errorMessage = "User already exists."; } } } ?>

Check if user already exists

The isMemberExists() function is used to check the user data uniqueness based on their email and the username. If the entered username or email there exists in the user database, then the registration process will be stopped by returning and acknowledgement.

This acknowledgement will notify that the “user already exists”. The code is,

Function isMemberExists($username, $email) { $query = "select * FROM registered_users WHERE user_name = ? OR email = ?"; $paramType = "ss"; $paramArray = array($username, $email); $memberCount = $this->ds->numRows($query, $paramType, $paramArray); return $memberCount; }

Insert member data to the database

If it returns 0 then it means that there is no such users exist with the email or the username entered. And so, the registration data will be inserted to the database. The following code shows the member insert method.

Function insertMemberRecord($username, $displayName, $password, $email) { $passwordHash = md5($password); $query = "INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)"; $paramType = "ssss"; $paramArray = array($username, $displayName, $passwordHash, $email); $insertId = $this->ds->insert($query, $paramType, $paramArray); return $insertId; }

DataSource.php

This is the generic data source class in PHP to perform database operations. It includes functions to connect database and execute various queries to get database result, row count, execute insert and more.

This datasource class is generic and kept as simple as possible. It is efficient and I use it in my most of the micro projects and tutorials. You are free to download and use it.

Important thing is never forget to use the Prepared Statements . It helps you to safeguard from SQL injection attacks and it is the first step in terms of implementing security in a web application.

conn = $this->getConnection(); } /** * If connection object is needed use this method and get access to it. * Otherwise, use the below methods for insert / update / etc. * * @return \mysqli */ public function getConnection() { $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME); if (mysqli_connect_errno()) { trigger_error("Problem with connecting to database."); } $conn->set_charset("utf8"); return $conn; } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function select($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($sql, $paramType, $paramArray); } $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset = $row; } } if (! empty($resultset)) { return $resultset; } } /** * To insert * @param string $query * @param string $paramType * @param array $paramArray * @return int */ public function insert($query, $paramType, $paramArray) { print $query; $stmt = $this->conn->prepare($query); $this->bindQueryParams($stmt, $paramType, $paramArray); $stmt->execute(); $insertId = $stmt->insert_id; return $insertId; } /** * To execute query * @param string $query * @param string $paramType * @param array $paramArray */ public function execute($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType="", $paramArray=array()); } $stmt->execute(); } /** * 1. Prepares parameter binding * 2. Bind prameters to the sql statement * @param string $stmt * @param string $paramType * @param array $paramArray */ public function bindQueryParams($stmt, $paramType, $paramArray=array()) { $paramValueReference = & $paramType; for ($i = 0; $i < count($paramArray); $i ++) { $paramValueReference = & $paramArray[$i]; } call_user_func_array(array($stmt, "bind_param"), $paramValueReference); } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function numRows($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $stmt->store_result(); $recordCount = $stmt->num_rows; return $recordCount; } }

Database script

This database script has the create statement for the registered_users table. Import this script in your development environment to run this code.

Table structure for table `registered_users` -- CREATE TABLE IF NOT EXISTS `registered_users` (`id` int(8) NOT NULL AUTO_INCREMENT, `user_name` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `password` varchar(25) NOT NULL, `email` varchar(55) NOT NULL, `gender` varchar(20) NOT NULL, PRIMARY KEY (`id`));

If the registration form validation fails, then the error message will be shown to the user as like as below.

Comments to “PHP User Registration Form (Sign up) with MySQL Database”

    Hi Vincy, I get the following errors when running the register code, please help.

    INSERT INTO registered_users (user_name, display_name, password, email) VALUES (?, ?, ?, ?)
    Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 136

    Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php:99 Stack trace: #0 C:\xampp\htdocs\PHP\JAMII-CASH\Member.php(83): Phppot\DataSource->insert(‘INSERT INTO reg…’, ‘ssss’, Array) #1 C:\xampp\htdocs\PHP\JAMII-CASH\index.php(20): Phppot\Member->insertMemberRecord(‘chuki10’, ‘Ray’, ‘202020’, ‘raf.yah.s.1@gma…’) #2 {main} thrown in C:\xampp\htdocs\PHP\JAMII-CASH\DataSource.php on line 99

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

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: REGISTRATION FORM
USERNAME:
EMAIL-ID:
PASSWORD:
RE-PASSWORD:

STEP 3: For Database connectivity using MySQL

Create a connect.php file for basic database connection use that default code as below

STEP 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 code

Похожие публикации