PHP allows you to create dynamic web forms, process user input, validate data, and respond to user interactions. Forms are most commonly used to collect data, such as contact forms, logins, or new user registrations. The example below displays the basic structure of an HTML form and a PHP script for secure processing.
When working with forms, two things are key: user experience and security. We must ensure proper validation on
the server side to prevent the entry of incorrect or malicious data. In the table below you will find advanced
examples for registration and login. Let us start with a simple example that accepts a name and an e-mail address.
We will use the POST method, as it is more secure for sending data to the server, where it will be processed by the
processing.php file.
processing.php using the POST
method.$_SERVER["REQUEST_METHOD"]).$_POST global array (table).htmlspecialchars() function, which prevents XSS attacks (injection of malicious
code) by converting special characters.For professional validation, we use the filter_var function, which securely checks the format of an
e-mail address. Let us look at an upgraded example of the processing.php file:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Reading and basic data protection
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
// Advanced validation
if (empty($name)) {
echo "Name is a required field.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid e-mail address format.";
} else {
echo "Thank you, " . $name . "! Your data has been successfully received.";
}
} else {
echo "Direct access to the script is not allowed.";
}
?>
This example represents a "master" form that includes practically all common input fields. You will learn how to accept text, numbers, dates, dropdown selections, and checkboxes using PHP.
Password protection is crucial for the security of user accounts and applications. In PHP, we use the
password_hash function, which offers robust and secure password storage.
This function uses the bcrypt algorithm by default, which is highly effective for this task. Steps
for password protection:
| Function | Purpose | When do we use it? |
|---|---|---|
| password_hash() | Creates a securely encrypted password (hash). | During new user registration. |
| password_verify() | Checks if the entered password matches the hash. | During existing user login. |
With these examples, we can ensure secure user login and registration in PHP using password_hash.
It is impossible to reverse an encrypted password back into its original form using the password_hash
function. password_hash uses a one-way algorithm to create passwords, meaning that the original password
cannot be reconstructed from its hash.
Before we can start storing users, we must prepare the appropriate table in our SQL database. It is crucial
that the password column is long enough (at least 255 characters), as the password_hash
function creates long strings of characters that must not be truncated.
<?php
$server = "localhost";
$username = "root"; // Username for the database connection
$password = ""; // Password for the database connection
$database = "mysqli_database"; // Name of your database
// Create connection
$connection = new mysqli($server, $username, $password, $database);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// SQL query to create a table
$table = "CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
// Create table
if ($connection->query($table) === TRUE) {
echo "The users table was successfully created!";
} else {
echo "Error creating table: " . $connection->error;
}
// Close connection
$connection->close();
?>
Note: Never use old algorithms like md5 or sha1 for passwords.
These are outdated and insecure today. Always use password_hash with the default algorithm
PASSWORD_DEFAULT.
Passwords must always be properly hashed before saving them to the database because, if a database breach occurs,
users should not be further compromised due to the disclosure of plain text passwords. PHP introduced the
password_hash function precisely for this reason and uses the latest secure algorithms to produce a
"hash". This function also handles salting automatically, meaning it adds random values to our password for
additional security. Usage example:
// user password $password = "MyVeryStrongPassword123!"; // hashing the password $passwordHash = password_hash($password, PASSWORD_DEFAULT); // output for storing in the database echo $passwordHash;
The PASSWORD_DEFAULT function currently uses the bcrypt algorithm, but it may
transition to a more secure default algorithm in the future if one becomes available. When a user enters their
password (e.g., during login), we use the password_verify function to compare the entered password
with the already stored "hash". Example:
// user password
$password = "MyVeryStrongPassword123!";
// hashing the password
$storedHash = "$2y$10$wYrFr1vZyxE/DoTGMNOxBritish5764JsqzBYzNOdcdWy1zqHmuUG8";
// verifying the password
if (password_verify($password, $storedHash)) {
echo "Password is correct.";
} else {
echo "Password is incorrect.";
}
It is important to know that password_verify returns true if they match, otherwise
it returns false. It is recommended to use BCRYPT or stronger algorithms, which is
what password_hash currently uses. However, you can explicitly choose other algorithms, e.g.,
PASSWORD_ARGON2I or PASSWORD_ARGON2ID, if you require a higher level of
security.
$hash = password_hash($password, PASSWORD_ARGON2I);
It is recommended to regularly update the hash. If we upgrade to a more complex algorithm, we can
utilize password_needs_rehash to check if the hash is outdated.
if (password_needs_rehash($storedHash, PASSWORD_ARGON2I)) {
$storedHash = password_hash($password, PASSWORD_ARGON2I);
}
Even the most secure hash will not help if the database or the application are vulnerable. It is necessary to ensure
the protection of the database (e.g., PDO and prepared statements to prevent SQL injections). There is no need to implement
your own custom mechanisms for additional salting, because the password_hash function handles
this by itself. As far as breaches are concerned, I recommend a very strong password for the database, because only that
way can we protect ourselves; if a breach does occur, it is necessary to notify all users to reset their passwords.
It is also recommended to implement monitoring for suspicious activities, such as repeated login attempts.
The password_hash function and accompanying functions, like password_verify and
password_needs_rehash, provide complete tools for working securely with passwords. Older methods like
md5 or sha1 must be avoided because they are no longer secure.