PHP сценарии обработки HTML форм. Создание и проверка форм Вкусный registration form php

Подписаться
Вступай в сообщество «vityazevo-pizz-and-roll.ru»!
ВКонтакте:

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 - то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел . Вот пример формы HTML:

Пример #1 Простейшая форма HTML

Ваше имя:

Ваш возраст:

В этой форме нет ничего особенного. Это обычная форма HTML без каких-либо специальных тегов. Когда пользователь заполнит форму и нажмет кнопку отправки, будет вызвана страница action.php . В этом файле может быть что-то вроде:

Пример #2 Выводим данные формы

Здравствуйте, .
Вам лет.

Пример вывода данной программы:

Здравствуйте, Сергей. Вам 30 лет.

Если не принимать во внимание куски кода с htmlspecialchars() и (int) , принцип работы данного кода должен быть прост и понятен. htmlspecialchars() обеспечивает правильную кодировку "особых" HTML-символов так, чтобы вредоносный HTML или Javascript не был вставлен на вашу страницу. Поле age, о котором нам известно, что оно должно быть число, мы можем просто преобразовать в integer , что автоматически избавит нас от нежелательных символов. PHP также может сделать это автоматически с помощью расширения filter . Переменные $_POST["name"] и $_POST["age"] автоматически установлены для вас средствами PHP. Ранее мы использовали суперглобальную переменную $_SERVER , здесь же мы точно так же используем суперглобальную переменную $_POST , которая содержит все POST-данные. Заметим, что метод отправки (method) нашей формы - POST. Если бы мы использовали метод GET , то информация нашей формы была бы в суперглобальной переменной $_GET . Кроме этого, можно использовать переменную $_REQUEST , если источник данных не имеет значения. Эта переменная содержит смесь данных GET, POST, COOKIE.

16 years ago

According to the HTTP specification, you should use the POST method when you"re using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it"s almost always an error -- you shouldn"t be posting the same comment twice -- which is why these pages aren"t bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything. For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.

2 years ago

Worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don"t want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don"t deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren"t many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS you minimise the risk of your users getting code (ADs) injected into your traffic that wasn"t put there by you.

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

Последнее обновление: 1.11.2015

Одним из основных способов передачи данных веб-сайту является обработка форм. Формы представляют специальные элементы разметки HTML, которые содержат в себе различные элементы ввода - текстовые поля, кнопки и т.д. И с помощью данных форм мы можем ввести некоторые данные и отправить их на сервер. А сервер уже обрабатывает эти данные.

Создание форм состоит из следующих аспектов:

    Создание элемента в разметке HTML

    Добавление в этот элемент одно или несколько поле ввода

    Установка метода передачи данных: GET или POST

    Установка адреса, на который будут отправляться введенные данные

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

Вход на сайт Логин:

Пароль:

Атрибут action="login.php" элемента form указывает, что данные формы будет обрабатывать скрипт login.php , который будет находиться с файлом form.php в одной папке. А атрибут method="POST" указывает, что в качестве метода передачи данных будет применяться метод POST.

Теперь создадим файл login.php , который будет иметь следующее содержание:

Чтобы получить данные формы, используется глобальная переменная $_POST . Она представляет ассоциативный массив данных, переданных с помощью метода POST. Используя ключи, мы можем получить отправленные значения. Ключами в этом массиве являются значения атрибутов name у полей ввода формы.

Так как атрибут name поля ввода логина имеет значение login (), то в массиве $_POST значение этого поля будет представлять ключ "login": $_POST["login"]

И поскольку возможны ситуации, когда поле ввода будет не установлено, например, при прямом переходе к скрипту: http://localhost:8080/login.php . В этом случае желательно перед обработкой данных проверять их наличие с помощью функции isset() . И если переменная установлена, то функция isset() возвратит значение true .

Теперь мы можем обратиться к форме:

И по нажатию кнопки введенные данные методом POST будут отправлены скрипту login.php :

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

Вход на сайт Логин:

Пароль:

Безопасность данных

Большое значение в PHP имеет организация безопасности данных. Рассмотрим несколько простых механизмов, которые могут повысить безопасность нашего веб-сайта.

Но вначале возьмем форму из прошлой темы и попробуем ввести в нее некоторые данные. Например, введем в поле для логина "alert(hi);", а в поле для пароля текст "пароль":

После отправки данных в html разметку будет внедрен код javascript, который выводит окно с сообщением.

Чтобы избежать подобных проблем с безопасностью, следует применять функцию htmlentities() :

If(isset($_POST["login"]) && isset($_POST["password"])){ $login=htmlentities($_POST["login"]); $password = htmlentities($_POST["password"]); echo "Ваш логин: $login
Ваш пароль: $password"; }

И даже после ввода кода html или javascript все теги будут экранированы, и мы получим следующий вывод:

Еще одна функция - функция strip_tags() позволяет полностью исключить теги html:

If(isset($_POST["login"]) && isset($_POST["password"])){ $login=strip_tags($_POST["login"]); $password = strip_tags($_POST["password"]); echo "Ваш логин: $login
Ваш пароль: $password"; }

Результатом ее работы при том же вводе будет следующий вывод.

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

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

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

Файл register.php

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

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

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

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

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

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

Пример скрипта регистрации register.php style.css" />

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

← Вернуться

×
Вступай в сообщество «vityazevo-pizz-and-roll.ru»!
ВКонтакте:
Я уже подписан на сообщество «vityazevo-pizz-and-roll.ru»