PHP Manual
/
Forms

Forms, form processing in PHP

22. 08. 2019

I suppose we have created an HTML form, which we send and now we want to process the data. There is a separate article about creating an HTML form.

Receiving data - different ways

The way the form is sent is set directly in the HTML

There are 2 options:

  • GET - It is visible in the address bar after the question mark For example: php.baraja.cz/search.php?query=formulare
  • POST - Hidden (not visible), most forms are sent via post

We then have to use the same method to read them in PHP.

Getting the data from the user and transferring it to the script

The basis is an HTML form, how to make it you can read in a separate article.

For starters, let's assume a simple form to enter the user's name:

<form action="welcome.php" method="GET">
Enter a name: <input type="text" name="username">
<input type="submit" value="submit">
</form>

A text box for entering a name and a submit button will appear. When the button is clicked, the contents of the field are sent to the script welcome.php.

Now for the actual processing in the welcome.php file:

$username = $_GET['username'];
echo 'The username entered is: ' . $username;

Note the special variable $_GET. This is a superglobal variable that contains data from the form and can be accessed as an array.

The problem with this solution, however, is that the received data is not secure and a similar form can be easily attacked. For example, a potential attacker can enter javascript code in the field instead of a name, which will be written to the page and executed.

Therefore, we must always sanitize any user data before outputting it into HTML code:

$username = $_GET['username'] ?? 'Unknown';
echo 'The specified name is: ' . htmlspecialchars($username);

Further processing

We can do anything with the received data and treat it like any ordinary variable.

For example, add the value in two fields:

echo $_GET['x'] + $_GET['y'];

Or save to file, database, email, ...

The following functions are useful for this:

  • file_put_contents - function to save data to a file
  • MD5 - checksum calculation, for example for passwords
  • Cookies - save data to cookies (small files inside the web browser)

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
Status:
All systems normal.
2024