PHP Form Handling


PHP Form Handling Interview with follow-up questions

1. What is PHP form handling and why is it important?

PHP form handling is the server-side process of receiving, validating, sanitizing, and acting on data submitted through an HTML form. It is important because:

  • User interaction: Forms are the primary mechanism for collecting user input — registrations, logins, search queries, orders, contact messages.
  • Data integrity: Validation ensures submitted data meets expected formats and constraints before it is stored or acted upon.
  • Security: Without proper handling, forms are entry points for SQL injection, XSS, CSRF, and file upload attacks.

The two HTTP methods used in forms:

  • GET — data appended to the URL as query parameters; suitable for search/filter forms; bookmarkable but length-limited and logged in server access logs.
  • POST — data sent in the request body; suitable for sensitive data (passwords, file uploads); not cached or bookmarked.

Modern PHP form handling pattern:

  1. Check the request method: if ($_SERVER['REQUEST_METHOD'] === 'POST')
  2. Validate input (type, length, format, required fields)
  3. Sanitize: strip/encode potentially harmful characters
  4. Process (store in DB, send email, etc.)
  5. Redirect after POST (PRG pattern) to prevent duplicate submissions on refresh

Frameworks like Laravel provide form request classes (php artisan make:request) that encapsulate validation rules cleanly and are tested independently.

↑ Back to top

Follow-up 1

Can you explain the difference between GET and POST methods?

Yes, the main difference between the GET and POST methods is how the data is sent to the server.

  • GET method: The data is appended to the URL as query parameters. It is visible in the URL and has limitations on the amount of data that can be sent. It is commonly used for retrieving data from the server.

  • POST method: The data is sent in the body of the HTTP request. It is not visible in the URL and can handle larger amounts of data. It is commonly used for submitting data to the server, such as form submissions.

Follow-up 2

How do you handle form validation in PHP?

Form validation in PHP involves checking the submitted form data to ensure it meets certain criteria or constraints. Here is a basic example of how form validation can be done in PHP:


In this example, the form data is retrieved using the $_POST superglobal. The data is then validated by checking if the required fields are not empty and if the email format is valid. Any validation errors are stored in an array. If there are no errors, the form can be processed.

Follow-up 3

What is the role of the $_REQUEST variable in PHP form handling?

The $_REQUEST variable in PHP is a superglobal that contains the contents of both $_GET, $_POST, and $_COOKIE arrays. It can be used to retrieve form data regardless of the HTTP method used (GET or POST). However, it is generally recommended to use $_GET or $_POST directly, depending on the specific use case, to ensure clarity and avoid potential security issues.

Follow-up 4

How can you prevent form resubmission in PHP?

To prevent form resubmission in PHP, you can use the Post/Redirect/Get (PRG) pattern. Here's how it works:

  1. When the form is submitted, process the form data and perform the necessary actions.
  2. After processing the form, redirect the user to another page using the header function and the Location header.

Here's an example:


By redirecting the user to another page after form submission, you prevent the form from being resubmitted if the user refreshes the page or navigates back and forth. The user will see the result of the form submission on the redirected page.

2. How do you handle file uploads in a PHP form?

File uploads in PHP use the $_FILES superglobal. The HTML form must have enctype="multipart/form-data" and method="POST".

HTML:





PHP processing:

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $file = $_FILES['document'];

    // Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload error: ' . $file['error']);
    }

    // Validate file type using finfo (not trusting client-supplied MIME type)
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file['tmp_name']);
    $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if (!in_array($mimeType, $allowedTypes, true)) {
        throw new RuntimeException('File type not allowed');
    }

    // Validate file size
    $maxSize = 5 * 1024 * 1024; // 5 MB
    if ($file['size'] > $maxSize) {
        throw new RuntimeException('File too large');
    }

    // Generate a safe filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safeFilename = bin2hex(random_bytes(16)) . '.' . $extension;
    $destination = '/var/www/uploads/' . $safeFilename;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        throw new RuntimeException('Failed to save file');
    }
}

Key security points interviewers expect:

  • Never trust $_FILES['name'] — always generate your own filename.
  • Use finfo to verify MIME type from the actual file content, not the browser-supplied $_FILES['type'].
  • Store uploads outside the web root, or use a CDN/object storage (S3) in production.
  • Set upload_max_filesize and post_max_size in php.ini appropriately.
↑ Back to top

Follow-up 1

What are the security considerations when handling file uploads?

When handling file uploads in PHP, there are several security considerations to keep in mind:

  1. Validate the file type: Use server-side validation to ensure that only allowed file types are uploaded. You can use functions like mime_content_type() or finfo_file() to check the MIME type of the file.

  2. Limit file size: Set a maximum file size limit to prevent users from uploading excessively large files. You can use the upload_max_filesize and post_max_size directives in the PHP configuration file (php.ini) to control the maximum file size.

  3. Sanitize file names: Avoid using user-provided file names directly. Instead, generate a unique file name and store the original file name in a database or associate it with the uploaded file.

  4. Store uploaded files outside the web root: Store uploaded files in a directory outside the web root to prevent direct access to the files.

  5. Use secure file permissions: Set appropriate file permissions to restrict access to the uploaded files.

By following these security practices, you can minimize the risk of file upload vulnerabilities.

Follow-up 2

How do you validate the file type of an uploaded file?

To validate the file type of an uploaded file in PHP, you can use the mime_content_type() function or the finfo_file() function. Here's an example:

$file = $_FILES['file'];

// Using mime_content_type()
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$fileType = mime_content_type($file['tmp_name']);

if (in_array($fileType, $allowedTypes)) {
    echo 'File type is valid.';
} else {
    echo 'Invalid file type.';
}

// Using finfo_file()
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$fileType = finfo_file($finfo, $file['tmp_name']);

if (in_array($fileType, $allowedTypes)) {
    echo 'File type is valid.';
} else {
    echo 'Invalid file type.';
}

finfo_close($finfo);

Make sure to define the $allowedTypes array with the allowed MIME types for your specific use case.

Follow-up 3

What is the maximum file size that can be uploaded in PHP and how can it be changed?

The maximum file size that can be uploaded in PHP is determined by two configuration directives: upload_max_filesize and post_max_size.

  • upload_max_filesize sets the maximum size of an individual file that can be uploaded.
  • post_max_size sets the maximum size of the entire POST data, including file uploads.

By default, both directives are set to 2 megabytes (2M).

To change the maximum file size, you can modify the php.ini file or use the ini_set() function in your PHP script.

Here's an example of changing the maximum file size to 10 megabytes (10M) using ini_set():

ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');

Note that changing these directives in the php.ini file affects the entire PHP installation, while using ini_set() only affects the current script execution.

3. What is CSRF attack and how can it be prevented in PHP form handling?

CSRF (Cross-Site Request Forgery) is an attack where a malicious site tricks an authenticated user's browser into sending a forged request to a target site. Because the browser automatically includes cookies (including session cookies), the target site cannot distinguish the forged request from a legitimate one.

Prevention in PHP:

1. Synchronizer Token Pattern (CSRF tokens) — primary defense Generate a random token per session, include it as a hidden form field, and validate it on submission:

// Generate and store token
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// In the form
echo '';

// On form submission
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    die('CSRF token mismatch');
}

Use hash_equals() instead of === to prevent timing attacks.

2. SameSite cookie attribute Set SameSite=Strict or SameSite=Lax on the session cookie. Modern browsers enforce this, preventing the cookie from being sent in cross-site requests.

session_set_cookie_params(['samesite' => 'Strict', 'secure' => true, 'httponly' => true]);

3. Custom request headers (for AJAX) For API endpoints, require a custom header (e.g., X-Requested-With: XMLHttpRequest). Browsers' CORS policy prevents cross-origin requests from setting arbitrary headers.

Framework support: Laravel provides CSRF middleware automatically via the VerifyCsrfToken middleware. Symfony uses the csrf_token() Twig function and validates via form components.

↑ Back to top

Follow-up 1

What is the role of tokens in preventing CSRF attacks?

Tokens play a crucial role in preventing CSRF attacks. A CSRF token is a unique value that is generated for each form and included as a hidden field in the form. When the form is submitted, the server verifies that the token matches the one stored in the session. If the tokens do not match, the server rejects the form submission.

By including a CSRF token in each form, it becomes extremely difficult for an attacker to forge a valid request because they would need to know the correct token value. This effectively prevents CSRF attacks by ensuring that form submissions originate from the same website and not from a malicious source.

Follow-up 2

Can you explain the concept of 'Same Origin Policy' and how it relates to CSRF?

The Same Origin Policy is a security concept implemented by web browsers to prevent web pages from making requests to a different origin (domain, protocol, or port) than the one from which they were loaded. This policy ensures that scripts running on one website cannot access or manipulate the content of another website.

CSRF attacks exploit the fact that browsers automatically include cookies in cross-site requests. By tricking a user into submitting a form on a different website, an attacker can perform actions on behalf of the user without their consent. The Same Origin Policy alone does not protect against CSRF attacks because the request is technically coming from the same origin.

To mitigate CSRF attacks, additional measures like CSRF tokens and SameSite attribute are used. These measures ensure that the request is not only from the same origin but also from the intended website, thereby preventing unauthorized actions.

Follow-up 3

What other security threats should be considered when handling forms in PHP?

When handling forms in PHP, there are several other security threats that should be considered:

  1. SQL Injection: Ensure that user input is properly sanitized and validated before using it in database queries. Use prepared statements or parameterized queries to prevent SQL injection attacks.

  2. Cross-Site Scripting (XSS): Validate and sanitize user input to prevent the execution of malicious scripts. Use output encoding or HTML escaping when displaying user-generated content.

  3. File Upload Vulnerabilities: Implement strict file validation and restrict file types, sizes, and locations to prevent malicious file uploads. Store uploaded files outside the web root directory to prevent direct access.

  4. Session Hijacking: Use secure session management techniques, such as regenerating session IDs after successful login, setting session cookie attributes, and using HTTPS to encrypt session data.

  5. Brute Force Attacks: Implement account lockouts, rate limiting, and strong password policies to protect against brute force attacks on login forms.

  6. Input Validation: Validate and sanitize all user input to prevent various types of attacks, such as command injection, path traversal, and code injection.

By considering these security threats and implementing appropriate measures, you can enhance the security of form handling in PHP.

4. How do you handle multi-page forms in PHP?

Multi-page (wizard) forms collect data across several steps. The session is the standard mechanism for persisting data between pages in PHP.

Basic session-based approach:

// Step 1 — collect name
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['form_step1'] = [
        'name' => filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS),
    ];
    header('Location: step2.php');
    exit;
}
// Step 2 — collect email, then finalize
session_start();
if (!isset($_SESSION['form_step1'])) {
    header('Location: step1.php'); // redirect back if step 1 missing
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = $_SESSION['form_step1']['name'];
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    // Save to database, send email, etc.
    unset($_SESSION['form_step1']); // clean up
    header('Location: confirmation.php');
    exit;
}

Best practices:

  • Always redirect after POST (Post/Redirect/Get pattern) to prevent duplicate submissions on browser refresh.
  • Validate data at each step before storing in session.
  • Clear session data once the form is complete.
  • Include a CSRF token at each step.
  • Provide a progress indicator and allow backward navigation without data loss.

Framework alternatives: Laravel's Livewire and multi-step form packages handle wizard forms with less boilerplate and built-in validation. Alpine.js or Vue.js can manage multi-step state on the client side, sending all data in a single final POST.

↑ Back to top

Follow-up 1

What is the role of sessions in handling multi-page forms?

Sessions play a crucial role in handling multi-page forms in PHP. They allow you to store and retrieve data across different pages of the form. By using sessions, you can maintain the state of the form and access the form data on subsequent pages. This is important because HTTP is a stateless protocol, and sessions provide a way to maintain state between different requests.

Follow-up 2

How do you maintain state between different pages of a multi-page form?

To maintain state between different pages of a multi-page form in PHP, you can use sessions. Sessions allow you to store data that can be accessed across multiple pages. Here is an example of how you can use sessions to maintain state:

// Page 1 - form.html





// Page 2 - page2.php






// Page 3 - page3.php

Follow-up 3

What are the challenges in handling multi-page forms and how can they be overcome?

Handling multi-page forms in PHP can come with some challenges. One challenge is maintaining the state of the form data between different pages. This can be overcome by using sessions to store and retrieve the form data. Another challenge is validating the form data on each page. You can overcome this challenge by implementing server-side validation for each page of the form. Additionally, handling errors and displaying appropriate error messages to the user can be a challenge. This can be overcome by implementing error handling mechanisms and providing clear error messages to the user.

5. What is form sanitization and why is it important?

Form sanitization is the process of cleaning user-submitted input to remove or neutralize characters and patterns that could cause harm if processed or stored. It is a complement to validation (which checks that data meets expected criteria) — both are necessary.

Why it matters:

  • Unsanitized input stored in a database and later echoed to the browser enables XSS (Cross-Site Scripting).
  • Unsanitized input inserted into SQL queries enables SQL injection.
  • Unsanitized filenames or paths enable directory traversal attacks.

PHP sanitization tools:

// Remove HTML tags and encode special characters for HTML output
$name = htmlspecialchars($_POST['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

// For database input: use prepared statements — do NOT use addslashes()
$stmt = $pdo->prepare('INSERT INTO users (name) VALUES (?)');
$stmt->execute([$_POST['name']]);

// filter_var for specific formats
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$url   = filter_var($_POST['url'],   FILTER_SANITIZE_URL);
$int   = filter_var($_POST['age'],   FILTER_SANITIZE_NUMBER_INT);

Important distinction:

  • Sanitization modifies the data (strips tags, encodes characters).
  • Validation checks the data and rejects it if invalid.
  • Escaping encodes data appropriately for the context (HTML, SQL, shell) at the point of use.

The modern consensus is: validate early, escape at the point of output (not at input). Using prepared statements for SQL, and htmlspecialchars() or a template engine for HTML output, is safer and cleaner than trying to sanitize all input upfront.

↑ Back to top

Follow-up 1

What is the difference between form sanitization and form validation?

Form sanitization and form validation are both important steps in handling user inputs, but they serve different purposes.

Form sanitization focuses on cleaning and filtering user inputs to remove any potentially harmful or unwanted data. It ensures that the data entered by users is safe and does not pose a security risk.

On the other hand, form validation is the process of checking whether the user inputs meet certain criteria or requirements. It ensures that the data entered by users is valid and meets the expected format or constraints. Form validation can include checking for required fields, validating email addresses, verifying numeric values, and more.

Follow-up 2

How do you sanitize user inputs in PHP?

In PHP, you can sanitize user inputs using various functions and techniques. Here are some common methods:

  1. Using the filter_var() function: PHP provides the filter_var() function, which can be used to sanitize different types of data. You can specify the type of sanitization you want to apply, such as filtering out HTML tags, removing special characters, or validating email addresses.

  2. Using the htmlentities() function: This function converts special characters to their HTML entities, preventing them from being interpreted as HTML or JavaScript code.

  3. Using prepared statements: When working with databases, you can use prepared statements with parameterized queries to sanitize user inputs and prevent SQL injection attacks.

It is important to choose the appropriate sanitization method based on the specific data and context in which it will be used.

Follow-up 3

What are some common PHP functions used for form sanitization?

There are several common PHP functions that can be used for form sanitization:

  1. filter_var(): This function can be used to sanitize various types of data, such as filtering out HTML tags, removing special characters, or validating email addresses.

  2. htmlentities(): This function converts special characters to their HTML entities, preventing them from being interpreted as HTML or JavaScript code.

  3. strip_tags(): This function removes HTML and PHP tags from a string, allowing only specific tags to be preserved.

  4. addslashes(): This function adds slashes before characters that need to be escaped, such as quotes, to prevent SQL injection attacks.

  5. htmlspecialchars(): This function converts special characters to their HTML entities, preventing them from being interpreted as HTML or JavaScript code.

It is important to choose the appropriate function based on the specific sanitization needs of your application.

Live mock interview

Mock interview: PHP Form Handling

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.