Basic Structure of Forms and Receiving Data with PHP

Web forms allow users to input information.
They are created with the HTML <form> tag, and the destination PHP file is specified using the action attribute.
There are mainly two methods for sending data:

  • GET: Sends data appended to the URL
  • POST: Sends data hidden in the HTTP request body

For example, here is a form to input a username.

<form action="" method="POST">
  <input type="text" name="username">
  <button type="submit">Submit</button>
</form>

<?php
$username = $_POST['username'] ?? '';
echo "Name: " . $username;
?>
  • $_POST is a “superglobal variable” associative array that holds data sent via POST.
  • ?? '' means that if username is not sent, assign an empty string.

This is how forms and PHP are connected to receive and process user input data.

Receiving Text Input Data and Validation

Text input is the most commonly used basic form element.
After receiving data in PHP, you perform “validation” to prevent user mistakes and malicious data.

Below is an example that receives a “name” and validates it.

<?php
$name = trim($_POST['name'] ?? ''); // Remove whitespace from beginning and end

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ($name === '') {
    $errors[] = "Name is required.";
  } elseif (mb_strlen($name) > 50) {
    $errors[] = "Name must be 50 characters or less.";
  }
}

if ($errors) {
  foreach ($errors as $error) {
    echo "<p style='color:red;'>$error</p>";
  }
} else {
  echo "Hello, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "!";
}
?>

<form action="test-x.php" method="POST">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name ?? '', ENT_QUOTES, 'UTF-8'); ?>">
  <button type="submit">Submit</button>
</form>
  • trim() removes unnecessary spaces at the start and end of the string.
  • mb_strlen() accurately counts multibyte characters like Japanese.
  • htmlspecialchars() safely converts special HTML characters (e.g., <, >, &) to prevent XSS attacks.

Validation ensures required fields are filled and length limits are respected, securing input safety and accuracy.

Handling Radio Buttons and Checkboxes in PHP

  • Radio buttons allow selecting only one option; PHP receives the value as a string.
  • Checkboxes allow multiple selections; PHP receives the values as an array.
  • If no value is sent, it will be empty (string or array), so prepare default values.
  • Always validate and apply XSS prevention to received values.

What Is a Radio Button?

Radio buttons are form elements to select only one option from multiple choices.
Used for selections like gender or age group.

Example of Radio Buttons

<form method="POST">
  <label><input type="radio" name="gender" value="male"> Male</label>
  <label><input type="radio" name="gender" value="female"> Female</label>
  <button type="submit">Submit</button>
</form>

Receiving and Validating in PHP

<?php
// Get the submitted gender; empty string if not sent
$gender = $_POST['gender'] ?? '';

// Check if the received value is an allowed option
if (!in_array($gender, ['male', 'female'], true)) {
  echo "Please select a gender.";
} else {
  // Display the selected value (escaping for XSS protection recommended)
  echo "Selected gender is \"" . htmlspecialchars($gender, ENT_QUOTES, 'UTF-8') . "\".";
}
?>

What Is a Checkbox?

Checkboxes are form elements that allow selecting any number of options.
Used to select multiple hobbies or interests.

Example of Checkboxes

Use [] in the name attribute to send as an array for multiple selections.

<form method="POST">
  <label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
  <label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
  <label><input type="checkbox" name="hobbies[]" value="reading"> Reading</label>
  <button type="submit">Submit</button>
</form>

Receiving and Validating in PHP

<?php
// Received array of hobbies; empty array if not sent
$hobbies = $_POST['hobbies'] ?? [];

if (empty($hobbies)) {
  echo "Please select at least one hobby.";
} else {
  // Escape each value safely and join with commas for display
  echo "Selected hobbies: " . implode(', ', array_map('htmlspecialchars', $hobbies)) . ".";
}
?>

How to Retrieve Selected Value from a Select Box (Dropdown)

A select box made with the <select> tag is a form element to select only one option from multiple choices.
Often used to select countries, prefectures, and similar lists. Always validate the submitted value in PHP to ensure it is correct. If the value is invalid or unselected, return an error and prompt the user to select. It’s also recommended to reflect the selected value back in the form to create a user-friendly interface.

Example of a Select Box

<form method="POST">
  <select name="country">
    <option value="">Please select</option>
    <option value="jp">Japan</option>
    <option value="us">United States</option>
    <option value="fr">France</option>
  </select>
  <button type="submit">Submit</button>
</form>
  • The name attribute of the <select> tag specifies the key name sent on submission.
  • The value attribute of each <option> tag is the value sent.
  • The first “Please select” option has an empty string "" to represent unselected.

Receiving the Value in PHP and Validity Check

<?php
// Get the value sent from the form; assign empty string if none
$country = $_POST['country'] ?? '';

// Array of valid choices
$validCountries = ['jp', 'us', 'fr'];

// Check if the submitted value is in the valid choices
if (!in_array($country, $validCountries, true)) {
  echo "Please select a valid country.";
} else {
  // Display the selected country value (escape for XSS protection recommended)
  echo "Selected country is \"" . htmlspecialchars($country, ENT_QUOTES, 'UTF-8') . "\".";
}
?>
  • $_POST['country'] ?? '' assigns an empty string if nothing was submitted.
  • in_array() checks if the submitted value is one of the predefined valid choices.
  • If invalid or unselected, an error message is shown.
  • If valid, the value is safely displayed using htmlspecialchars().

How to Create File Upload Forms and Use Them Safely

To receive images or files on your website, use a “file upload form.”
Create a file selection button inside the form and send the selected file to the server.

How to Create a File Upload Form

<form method="POST" enctype="multipart/form-data">
  <input type="file" name="upload_file">
  <button type="submit">Upload</button>
</form>
  • <input type="file"> creates a button to select files.
  • enctype="multipart/form-data" is required when sending files.

How to Receive Files in PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload_file'])) {
  $file = $_FILES['upload_file'];

  // Check for upload errors
  if ($file['error'] !== UPLOAD_ERR_OK) {
    echo "Upload failed.";
    exit;
  }

  // Limit file size to 5MB
  if ($file['size'] > 5 * 1024 * 1024) {
    echo "File is too large. Please upload up to 5MB.";
    exit;
  }

  // Allowed file types (images only here)
  $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  if (!in_array($file['type'], $allowedTypes, true)) {
    echo "Only image files (jpg, png, gif) can be uploaded.";
    exit;
  }

  // Create a safe filename (do not use original name)
  $safeName = uniqid() . '-' . basename($file['name']);

  // Destination folder for files (uploads folder)
  $uploadDir = __DIR__ . '/uploads/';

  // Move the file to the server folder
  if (!move_uploaded_file($file['tmp_name'], $uploadDir . $safeName)) {
    echo "Failed to save the file.";
    exit;
  }

  echo "File uploaded successfully!";
}
?>

Key Points for Safe File Upload Usage

  • Restrict allowed file types and reject others
    For example, allow only images.
  • Do not use the original file name directly; rename files safely
    Prevents malicious or strange file names.
  • Set an upper limit for file size
    To avoid overloading the server.
  • Store uploaded files in safe locations
    For example, configure so PHP files cannot be executed accidentally.

File uploads are convenient but potentially dangerous if handled improperly. Follow these points to use them safely.

Examples of Using Form Data in PHP and Security Points

Data submitted from web forms can be used for purposes such as:

  • Storing in a database for later use
  • Sending notifications to administrators by email
  • Displaying input content on the screen for user confirmation

However, form input may contain malicious or incorrect data. Therefore, it is essential to follow these points for safe handling.

1. Input Validation

  • Required fields must be filled
  • Check that the text length is not too long or too short
  • Verify correct format for email addresses, numeric check for phone numbers, etc.

These checks help prevent user mistakes and malicious data in advance.

2. Escape Processing

Displaying form data directly on the page is dangerous if malicious code (e.g., <script> tags) is included.
Therefore, when displaying data, use functions like htmlspecialchars() to safely convert special characters. This prevents XSS (Cross-Site Scripting) attacks.

3. SQL Injection Prevention

When saving input data to a database, there is a risk of malicious SQL statements being injected.
To prevent this,

  • Use prepared statements
  • Or sanitize special characters with escape functions

These are essential practices.

4. CSRF Protection (Cross-Site Request Forgery)

There is an attack where malicious sites submit your forms without your knowledge.
To prevent this,

  • Include a random string called a “token” in the form and send it
  • Check that the received token is correct on the server side

This method is used for protection.

5. Safe Management of File Uploads

When allowing file uploads, as explained before, it is important to

  • Check the file type and size
  • Rename files to safe names
  • Store uploads in secure locations

These points are crucial.