Registration Form

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

Одно из главнейших достоинств PHP — то, как он работает с формами HTML. Здесь основным является то, что каждый элемент формы автоматически становится доступным вашим программам на PHP. Для подробной информации об использовании форм в PHP читайте раздел Переменные из внешних источников. Вот пример формы HTML:

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

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

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

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

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

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

В PHP можно также работать и с XForms, хотя вы найдёте работу с обычными HTML-формами довольно комфортной уже через некоторое время. Несмотря на то, что работа с XForms не для новичков, они могут показаться вам интересными. В разделе возможностей PHP у нас также есть короткое введение в обработку данных из XForms.

User Contributed Notes 3 notes

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.

Also, don’t ever use GET method in a form that capture passwords and other things that are meant to be hidden.

Читайте также:  Saving data with javascript

Источник

How to Create a Simple HTML and PHP Form

David Clinton

David Clinton

How to Create a Simple HTML and PHP Form

If you have a website, it’s only a matter of time before you feel the irrepressible urge to gather information about your site’s users.

The most direct way to do that is to ask them some questions. And, in the HTML world, the best tool for recording the answers to those questions is the simple HTML form.

In this guide, I’m going to show you how that’s done using basic HTML and just a dash of PHP.

As you’ll soon see, the HTML you’ll need to present a form is, in fact, pretty straightforward. But that’ll only solve half of your problem.

A form will prompt users to enter whatever information you’re asking for. But, if we leave it there, nothing will actually happen when they hit the Submit button. And that’s because we don’t have anything running on our server to collect and process that information.

Building the back end that’ll integrate your form with a database engine or an associated application can get really complicated and is way beyond our scope here. But, once we understand the HTML form here, I will show you how you can add some PHP code to handle the code in a basic way.

This article comes from my Complete LPI Web Development Essentials Study Guide course. If you’d like, you can follow the video version here:

form_html

Feel free to type something into the Name, Email, and Message fields, but there’s no point hitting the Submit button just yet. That’s because, without some PHP magic, nothing will happen. And I haven’t shown you that PHP yet.

How to Write a PHP Script to Capture User Inputs

PHP, by the way, is a web-friendly scripting language that’s a popular choice for adding programmed functionality to web pages. In fact, you can even incorporate PHP code directly into your HTML code. But here’s how it’ll look on its own, in a file called submit.php :

"; echo "Email: " . $email . "
"; echo "Message: " . $message . "
"; > ?>

Remember how our HTML post method sent the form data to this file? Well here’s what PHP is going to do with it. The if block looks for posted data and then organizes it by field: name, email, and message. Normally, you’d probably send that data along to a database but, for simplicity, this code will just print it back to the page to prove that we actually had it.

Let’s see what that’ll look like. I click the Submit button and the form is replaced by the text I’d entered. Nothing spectacular, but it does nicely illustrate how forms work with PHP.

results

With this simple code, you’re now able to create your own HTML forms that collect and process user input.

Your next step will be to connect with a back end database so you can save and manipulate that data. For for now, enjoy this accomplishment!

Читайте также:  Passing value to php function

Источник

PHP Registration Form using GET, POST Methods with Example

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.

PHP Form

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.

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

First name:
Last name:

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

Create a 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.
  • The array variable can be accessed from any script in the program; it has a global scope.
  • 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.

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

GET vs POST Methods

GET vs POST Methods

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

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

     

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

Simple Search Engine

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

The following will be shown

Simple Search Engine

The diagram below shows the URL for the above results

Simple Search Engine

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

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

View the above form in a browser

Working with Check boxes, Radio buttons

Fill in the first and last names

Note the Agree to Terms of Service checkbox has not been selected.

You will get the following results

Working with Check boxes, Radio buttons

Click on back to the form link and then select the checkbox

Working with Check boxes, Radio buttons

You will get the following results

Working with Check boxes, Radio buttons

Summary

  • Forms are used to get data from the users
  • Forms are created using HTML tags
  • Forms can be submitted to the server for processing using either POST or GET method
  • Form values submitted via the POST method are encapsulated in the HTTP body.
  • Form values submitted via the GET method are appended and displayed in the URL.

Источник

Оцените статью