Form Handling
Form Handling Interview with follow-up questions
1. What is form handling in PHP and why is it important?
Form handling in PHP refers to the server-side process of receiving, validating, sanitizing, and acting on data submitted through an HTML form. It is a fundamental part of web development because forms are the primary mechanism for collecting and processing user input.
Why it matters:
- Forms handle user authentication, search queries, order submissions, profile updates, file uploads, and more.
- PHP's superglobals (
$_GET,$_POST,$_FILES) provide direct access to submitted form data. - Proper handling prevents security vulnerabilities: SQL injection, XSS, CSRF, and malicious file uploads.
The core process:
- Present the form — HTML form with
method(GET or POST) andaction(target URL). - Receive data — Access via
$_GET,$_POST, or$_FILES. - Validate — Check types, lengths, formats, required fields.
- Sanitize/escape — Prepare data for the appropriate context (HTML output, database storage).
- Process — Save to database, send email, trigger a workflow.
- Respond — Redirect (PRG pattern) or render a success/error page.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) {
$errors[] = 'Invalid email address';
} else {
saveSubscriber($email);
header('Location: /success');
exit;
}
}
Modern approach: Laravel's form request validation classes (php artisan make:request) and Symfony's Form component encapsulate this entire pipeline cleanly, with built-in validation, error messages, and CSRF protection.
Follow-up 1
What are the different methods used in form handling?
There are two main methods used in form handling: GET and POST.
GET method: This method appends the form data to the URL as query parameters. It is commonly used for retrieving data from the server. However, it is not suitable for handling sensitive information as the data is visible in the URL.
POST method: This method sends the form data in the body of the HTTP request. It is more secure than the GET method as the data is not visible in the URL. It is commonly used for submitting sensitive information, such as passwords or credit card details.
Follow-up 2
What is the difference between GET and POST methods?
The main differences between the GET and POST methods in form handling are as follows:
Data Visibility: GET method appends the form data to the URL, making it visible in the browser's address bar, while POST method sends the data in the body of the HTTP request, keeping it hidden from the URL.
Data Length: GET method has a limitation on the length of the data that can be sent, typically around 2048 characters, while POST method has no such limitation.
Caching: GET requests can be cached by the browser, while POST requests are not cached.
Security: POST method is more secure than GET method as the data is not visible in the URL. It is recommended to use POST method for handling sensitive information.
Follow-up 3
How can you validate form data in PHP?
In PHP, you can validate form data using various techniques:
Server-side validation: This involves validating the form data on the server side using PHP code. You can use functions like
isset(),empty(),filter_var(), and regular expressions to validate the data.Client-side validation: This involves validating the form data on the client side using JavaScript. You can use JavaScript libraries like jQuery or HTML5 form validation attributes like
required,pattern, andminlengthto validate the data.
It is recommended to perform both server-side and client-side validation to ensure data integrity and security.
Follow-up 4
What are some common security threats with form handling and how can they be mitigated?
Some common security threats with form handling in PHP are:
Cross-Site Scripting (XSS): This occurs when an attacker injects malicious scripts into the form data, which can be executed by other users. To mitigate XSS attacks, you should always sanitize and validate user input, and use output escaping functions like
htmlspecialchars()when displaying the data.Cross-Site Request Forgery (CSRF): This occurs when an attacker tricks a user into submitting a form without their consent. To mitigate CSRF attacks, you can use techniques like CSRF tokens, checking the referrer header, and implementing CAPTCHA.
SQL Injection: This occurs when an attacker injects malicious SQL queries into the form data, which can manipulate the database. To mitigate SQL injection attacks, you should always use prepared statements or parameterized queries to handle database interactions.
File Upload Vulnerabilities: This occurs when an attacker uploads malicious files through a form. To mitigate file upload vulnerabilities, you should validate file types, restrict file size, and store uploaded files in a secure location.
It is important to implement proper security measures and follow best practices to protect against these threats.
2. How can you handle file uploads in a form using PHP?
File uploads in PHP require the form's enctype attribute to be set to multipart/form-data and use the $_FILES superglobal on the server side.
HTML:
Upload
PHP — secure file upload handler:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = $_FILES['avatar'];
// 1. Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload error code: ' . $file['error']);
}
// 2. Validate size
if ($file['size'] > 2 * 1024 * 1024) { // 2 MB limit
throw new RuntimeException('File exceeds size limit');
}
// 3. Validate MIME type by reading file content (not the browser header)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file['tmp_name']);
if (!in_array($mimeType, ['image/jpeg', 'image/png', 'image/webp'], true)) {
throw new RuntimeException('File type not permitted');
}
// 4. Generate a safe filename
$ext = match($mimeType) {
'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp',
};
$safeFilename = bin2hex(random_bytes(16)) . '.' . $ext;
// 5. Move from temp to upload directory (outside web root is best practice)
$uploadPath = '/var/uploads/' . $safeFilename;
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
throw new RuntimeException('Failed to move uploaded file');
}
}
Key security rules: Never trust $_FILES['type'] (browser-supplied, easily spoofed); always use finfo; generate random filenames; store outside the web root when possible.
Follow-up 1
What are the security considerations when handling file uploads?
When handling file uploads, there are several security considerations to keep in mind:
Validate the file type: Use the
$_FILESarray'stypeproperty or a file validation library to ensure that the uploaded file has the expected file type. This helps prevent users from uploading malicious files.Limit file size: Set a maximum file size limit using the
upload_max_filesizeandpost_max_sizedirectives in PHP configuration or by validating the file size in your PHP script. This prevents users from uploading excessively large files that may consume server resources.Sanitize file names: Before using the uploaded file's name, sanitize it to remove any potentially malicious characters or path traversal sequences. This helps prevent directory traversal attacks.
Store uploaded files outside the web root: Save uploaded files in a directory outside the web root to prevent direct access to the files by users.
Use secure file permissions: Set appropriate file permissions on the uploaded files to restrict access to them.
Scan uploaded files for viruses: Consider using antivirus software or libraries to scan uploaded files for viruses or malware.
By implementing these security measures, you can help protect your application and server from potential vulnerabilities associated with file uploads.
Follow-up 2
How can you limit the size of the file being uploaded?
To limit the size of the file being uploaded, you can use the upload_max_filesize and post_max_size directives in the PHP configuration file (php.ini) or by validating the file size in your PHP script.
- Using php.ini:
- Open the php.ini file.
- Locate the
upload_max_filesizeandpost_max_sizedirectives. - Set their values to the desired maximum file size in bytes.
For example, to set the maximum file size to 10 megabytes:
upload_max_filesize = 10M
post_max_size = 10M
- Using PHP script:
$maxFileSize = 10 * 1024 * 1024; // 10 megabytes
if ($_SERVER['CONTENT_LENGTH'] > $maxFileSize) {
echo 'File size exceeds the maximum limit.';
exit;
}
By setting the maximum file size, you can prevent users from uploading files that exceed the specified limit.
Follow-up 3
How can you restrict the type of file being uploaded?
To restrict the type of file being uploaded, you can validate the file's MIME type or file extension.
- Validating MIME type:
$allowedMimeTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($_FILES['file']['type'], $allowedMimeTypes)) {
echo 'Invalid file type.';
exit;
}
- Validating file extension:
$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
$uploadedFileExtension = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
if (!in_array($uploadedFileExtension, $allowedExtensions)) {
echo 'Invalid file extension.';
exit;
}
By validating the file's MIME type or extension, you can ensure that only files of the specified types are allowed to be uploaded.
3. What is the role of the $_SERVER['PHP_SELF'] variable in form handling?
$_SERVER['PHP_SELF'] contains the filename of the currently executing script, relative to the document root, including any path info. It is often used as the action attribute value for a self-submitting form — a form that submits back to the same script that rendered it.
alert(1)
which would cause $_SERVER['PHP_SELF'] to contain ">alert(1) — injecting XSS into your form's action attribute.
Fix: Always escape with htmlspecialchars():
action="= htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') ?>"
Modern alternative: Many developers prefer hardcoding the action URL or using the framework's route helper, which avoids this concern entirely:
// Laravel
Follow-up 1
What are the security risks associated with using $_SERVER['PHP_SELF']?
Using $_SERVER['PHP_SELF'] directly in the action attribute of a form can pose security risks, as it can make your application vulnerable to cross-site scripting (XSS) attacks. An attacker can manipulate the value of the action attribute to inject malicious code into your application, which can then be executed by unsuspecting users. This can lead to unauthorized access, data theft, and other security breaches.
Follow-up 2
How can you mitigate these risks?
To mitigate the security risks associated with using $_SERVER['PHP_SELF'], it is recommended to sanitize and validate the input received from the action attribute. One way to do this is by using the htmlspecialchars() function to convert special characters to their HTML entities. For example, you can use the following code snippet to sanitize the action attribute:
$action = htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8');
Additionally, it is good practice to use server-side form validation to ensure that the submitted data meets the required criteria. This can help prevent malicious code from being executed even if the action attribute is manipulated.
4. How can you retain form data after the form is submitted?
Retaining form data after submission is important for improving user experience, especially when validation fails and the user must correct their input.
1. Re-populate form fields from POST data (most common pattern):
// On validation failure, redisplay the form with values filled in
$name = htmlspecialchars($_POST['name'] ?? '');
$email = htmlspecialchars($_POST['email'] ?? '');
2. Session storage (for multi-page forms or after redirect):
// Store form data in session on validation failure
$_SESSION['form_data'] = $_POST;
$_SESSION['errors'] = $errors;
header('Location: /form');
exit;
// On the form page, repopulate from session
$formData = $_SESSION['form_data'] ?? [];
$name = htmlspecialchars($formData['name'] ?? '');
unset($_SESSION['form_data'], $_SESSION['errors']); // clean up after reading
3. Hidden form fields (for wizard forms): Pass previously collected data forward as hidden inputs across steps:
4. Client-side storage (for draft/autosave):
JavaScript localStorage or sessionStorage can save form progress as the user types:
document.querySelector('form').addEventListener('input', () => {
localStorage.setItem('draft', JSON.stringify(getFormValues()));
});
PRG Pattern (Post/Redirect/Get): After successful processing, always redirect to prevent duplicate submissions on browser refresh. Store confirmation messages in session flash data.
Follow-up 1
What is the benefit of retaining form data?
The benefit of retaining form data is that it provides a better user experience. When a form is submitted and the data is retained, the user does not have to re-enter all the information again if there was an error or if they need to make changes. It saves time and effort for the user and reduces the chances of errors or frustration.
Follow-up 2
What are some scenarios where retaining form data would be useful?
Retaining form data can be useful in various scenarios, including:
E-commerce websites: When a user adds items to their shopping cart and proceeds to the checkout page, retaining the form data allows them to easily make changes to the order without having to re-enter all the information.
Multi-step forms: If a form is divided into multiple steps, retaining the form data allows the user to go back and forth between the steps without losing the entered information.
User registration: When a user is registering on a website and there are validation errors, retaining the form data allows them to correct the errors without having to fill in all the fields again.
Contact forms: Retaining form data in contact forms allows users to easily send multiple messages without having to re-enter their name, email, and other details every time.
These are just a few examples, but retaining form data can be beneficial in any situation where users need to submit and modify data through a form.
5. How can you handle multiple form inputs with the same name?
When multiple form inputs share the same name, PHP normally only keeps the last submitted value. To collect all values as an array, append [] to the input name:
HTML:
PHP
JavaScript
Python
Submit
PHP:
$interests = $_POST['interests'] ?? [];
// $interests = ['php', 'javascript'] if those two were checked
foreach ($interests as $interest) {
echo htmlspecialchars($interest) . "\n";
}
Named indices:
foreach ($_POST['user'] as $u) {
echo $u['name'] . ': ' . $u['email'];
}
Validation: When receiving array input, validate each element individually:
$allowedInterests = ['php', 'javascript', 'python'];
$interests = array_filter(
$_POST['interests'] ?? [],
fn($v) => in_array($v, $allowedInterests, true)
);
Always validate array inputs — an attacker can send any values in a [] field, not just the ones your form presents.
Follow-up 1
What is the purpose of handling multiple form inputs with the same name?
Handling multiple form inputs with the same name is useful when you have a dynamic number of input fields or when you want to group related inputs together. It allows you to easily process and manipulate the values of these inputs as an array in PHP.
Follow-up 2
How can you retrieve the values of these inputs in PHP?
To retrieve the values of form inputs with the same name in PHP, you can use the $_POST or $_GET superglobal arrays. Since the inputs have the same name and are treated as an array, you can access their values using the array syntax. For example:
$inputValues = $_POST['input_name'];
foreach ($inputValues as $value) {
echo $value;
}
Live mock interview
Mock interview: Form Handling
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
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.