Consider this PHP script that processes a form submission. What will it output when the form is submitted with name=John?
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? 'Guest'; echo "Hello, $name!"; } else { echo "Please submit the form."; } ?>
Check the request method and how the $_POST array is used.
The script checks if the request method is POST. If yes, it reads the 'name' from $_POST. Since the form sends 'name=John', it outputs 'Hello, John!'.
Given this PHP code snippet, what will be the output if the form is submitted using the GET method with name=Alice?
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo "Hello, " . htmlspecialchars($_POST['name']) . "!"; } else { echo "Form not submitted via POST."; } ?>
Look at the condition checking the request method.
The code only processes the form if the request method is POST. Since the form uses GET, it skips the POST block and outputs 'Form not submitted via POST.'
Examine this PHP code snippet. When the form is submitted without the 'email' field, it shows an error. What causes this error?
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $email = $_POST['email']; echo "Email: $email"; } ?>
Think about what happens if a key is missing in the $_POST array.
If the form is submitted without the 'email' field, $_POST['email'] does not exist. Accessing it directly causes a PHP notice 'Undefined index'.
What is the syntax error in this PHP snippet that handles form data?
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; echo "User: $username"; } else { echo "No data received." } ?>
Check the end of each statement carefully.
The else block's echo statement lacks a semicolon at the end, causing a syntax error.
Given this HTML form and PHP script, how many key-value pairs will $_POST contain after submission?
HTML form:
<form method="POST" action="submit.php"> <input type="text" name="first_name" value="Anna" /> <input type="text" name="last_name" value="Smith" /> <input type="checkbox" name="subscribe" value="yes" checked /> <input type="checkbox" name="subscribe" value="no" /> <input type="submit" value="Send" /> </form>
PHP snippet (submit.php):
<?php print_r($_POST); ?>
Remember how checkboxes with the same name behave in form submission.
Only the checked checkbox with name 'subscribe' and value 'yes' is sent. The form sends 'first_name', 'last_name', and one 'subscribe' value, so $_POST has 3 keys: 'first_name', 'last_name', 'subscribe'. Correct answer: B.