Core PHP 7 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Send HTML form data to a PHP script and read it with $_POST, $_GET and $_REQUEST.
  • Choose between the GET and POST methods.
  • Safely display user input with htmlspecialchars().
  • Build a self-processing form and handle checkboxes, radio buttons and select lists.
Forms and PHP

The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page is automatically available to your PHP scripts. The name attribute of each field becomes the key in the superglobal array $_POST or $_GET.

The example below contains an HTML form with two input fields and a submit button:

File: htdocs/phpbook/ch11/form.html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age" size="4">
<input type="submit">
</form>
</body>
</html>
OUTPUT browser · http://localhost/phpbook/ch11/form.html
Browser output

When a user fills out the form and clicks the submit button, the form data is sent to the PHP file welcome.php:

File: htdocs/phpbook/ch11/welcome.php
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
OUTPUT browser · after typing John and 28 in form.html and clicking Submit → welcome.php
Welcome John!
You are 28 years old.
The GET Method and $_GET

The built-in $_GET array collects values from a form sent with method="get". Information sent with GET is visible to everyone – it is displayed in the browser's address bar – and there is a limit on the amount of information.

File: htdocs/phpbook/ch11/form_get.html
<form action="welcome_get.php" method="get">
Name: <input type="text" name="fname">
Age: <input type="text" name="age" size="4">
<input type="submit">
</form>
OUTPUT browser · http://localhost/phpbook/ch11/form_get.html
Browser output

When the user clicks "Submit", the URL sent to the server looks like this:

http://localhost/phpbook/ch11/welcome_get.php?fname=Peter&age=37

The welcome_get.php file uses $_GET to collect the form data (the names of the form fields automatically become the keys of the $_GET array):

File: htdocs/phpbook/ch11/welcome_get.php
Welcome <?php echo $_GET["fname"]; ?>.<br>
You are <?php echo $_GET["age"]; ?> years old!
OUTPUT browser · http://localhost/phpbook/ch11/welcome_get.php?fname=Peter&age=37
Welcome Peter.
You are 37 years old!
When to use method="get"
  • All variable names and values are displayed in the URL, so the page can be bookmarked – useful for search pages and links.
  • Never use GET to send passwords or other sensitive information.
  • GET is not suitable for large values; keep URLs under about 2000 characters.
The POST Method and $_POST

The built-in $_POST array collects values from a form sent with method="post". Information sent with POST is invisible to others (it travels in the body of the HTTP request) and has no practical limit on the amount of information.

There is a maximum size for POST data, set by post_max_size in php.ini (XAMPP: 40M; PHP's own default is 8M). File uploads are also limited by upload_max_filesize.

When the user submits a POST form the URL shows only http://localhost/phpbook/ch11/welcome.php.

When to use method="post"
  • For passwords, personal data, large text and file uploads.
  • For actions that change data – inserting, updating or deleting records.
  • Because the variables are not in the URL, the page cannot be bookmarked.
The $_REQUEST Array

$_REQUEST contains the contents of $_GET, $_POST and $_COOKIE, so it can collect form data sent with either method:

File: htdocs/phpbook/ch11/welcome_req.php
Welcome <?php echo $_REQUEST["fname"]; ?>!<br>
You are <?php echo $_REQUEST["age"]; ?> years old.
OUTPUT browser · POST http://localhost/phpbook/ch11/welcome_req.php (fname=Meera&age=24)
Welcome Meera!
You are 24 years old.
GET vs POST at a glance

GET – data in the URL, visible, bookmarkable, size-limited, for reading/searching. POST – data in the request body, not visible in the URL, not bookmarkable, large data and files, for sending and changing data.

Displaying User Input Safely

Never echo user input directly. If a visitor types HTML or JavaScript – for example <script>alert('hi')</script> – it would run in the browser of everyone who views the page (Cross-Site Scripting, XSS). htmlspecialchars() converts <, >, &, " and ' into HTML entities so that the text is displayed, not executed.

File: htdocs/phpbook/ch11/safe.php
<?php
$msg = $_GET['msg'] ?? '';
echo "Unsafe length of input: " . strlen($msg) . "<br>";
echo "Safe display: " . htmlspecialchars($msg);
?>
OUTPUT browser · http://localhost/phpbook/ch11/safe.php?msg=%3Cb%3EHello%3C/b%3E%20%3Cscript%3Ealert(1)%3C/script%3E
Unsafe length of input: 38
Safe display: <b>Hello</b> <script>alert(1)</script>
A Self-Processing Form

A form can post to itself. The script checks whether the form has been submitted; if not, it shows the form, otherwise it processes the data. $_SERVER['PHP_SELF'] (escaped with htmlspecialchars()) gives the address of the current script.

File: htdocs/phpbook/ch11/selfform.php
<?php
$name = $course = $gender = "";
$hobbies = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name    = htmlspecialchars($_POST["name"] ?? "");
    $course  = htmlspecialchars($_POST["course"] ?? "");
    $gender  = htmlspecialchars($_POST["gender"] ?? "");
    $hobbies = $_POST["hobby"] ?? [];          // checkboxes arrive as an array
}
?>
<html><body style="font-family:Arial;font-size:13px">
<form method="post" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
  Name: <input type="text" name="name" id="n" value="<?= $name ?>"><br>
  Course:
  <select name="course" id="c">
    <option>BCA</option><option>MCA</option><option>B.Tech</option>
  </select><br>
  Gender:
  <input type="radio" name="gender" value="Male" id="g1">Male
  <input type="radio" name="gender" value="Female" id="g2">Female<br>
  Hobbies:
  <input type="checkbox" name="hobby[]" value="Reading" id="h1">Reading
  <input type="checkbox" name="hobby[]" value="Music" id="h2">Music
  <input type="checkbox" name="hobby[]" value="Cricket" id="h3">Cricket<br>
  <input type="submit" value="Register" id="s">
</form>
<?php if ($_SERVER["REQUEST_METHOD"] == "POST"): ?>
  <hr>
  <b>Registered:</b> <?= $name ?>, <?= $course ?>, <?= $gender ?><br>
  <b>Hobbies:</b> <?= htmlspecialchars(implode(", ", $hobbies)) ?>
<?php endif; ?>
</body></html>
OUTPUT browser · selfform.php after filling and submitting the form
Browser output
Name:
Course:
BCA
MCA
B.Tech

Gender: Male Female
Hobbies: Reading Music Cricket

Registered: Kavita, MCA, Female
Hobbies: Reading, Cricket
  • A group of checkboxes uses a name ending in [] (hobby[]); PHP then receives all checked values as an array.
  • Only checked checkboxes and the selected radio button are sent. Use ?? '' or isset() to avoid warnings when nothing is selected.
Key Takeaways
  • Form fields are available in PHP through $_POST, $_GET or $_REQUEST, keyed by the field's name.
  • GET puts data in the URL (visible, bookmarkable, limited); POST sends it in the request body.
  • $_REQUEST merges GET, POST and COOKIE data.
  • Always escape output with htmlspecialchars() to prevent XSS.
  • A self-processing form checks $_SERVER["REQUEST_METHOD"]; checkbox groups use name="x[]".
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch11 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : Every form field with a name attribute is sent to the script named in the form's action attribute and is available in $_POST, $_GET or $_REQUEST, with the field name as the key.

Answer : action gives the URL of the script that processes the data; method specifies how the data is sent – GET (in the URL) or POST (in the request body).

Answer : A superglobal associative array containing the variables passed in the URL query string, for example from a form with method="get".

Answer : The field names and values are appended after a question mark and separated by &, e.g. welcome_get.php?fname=Peter&age=37.

Answer : For requests that only read data, such as searches and filters, where bookmarking the result page is useful – never for passwords or sensitive data, and only for small amounts of data.

Answer : A superglobal associative array containing the variables sent in the body of an HTTP POST request, for example from a form with method="post".

Answer : Data is not shown in the URL, there is no practical size limit (only post_max_size), and it can carry binary data such as uploaded files.

Answer : post_max_size (XAMPP sets 40M; PHP's default is 8M). upload_max_filesize limits each uploaded file.

Answer : A superglobal array that contains the contents of $_GET, $_POST and $_COOKIE together, so a script can read a value without caring how it was sent.

Answer : XSS happens when user-supplied HTML/JavaScript is output into a page and runs in other users' browsers. Prevent it by escaping output with htmlspecialchars().

Answer : A form whose action is the same script (e.g. htmlspecialchars($_SERVER['PHP_SELF'])). The script shows the form and, when $_SERVER['REQUEST_METHOD'] is POST, processes the submitted data on the same page.

Answer : Name the checkboxes with square brackets, e.g. name="hobby[]"; PHP then provides $_POST['hobby'] as an array of the checked values.

Answer : Unchecked checkboxes, unselected radio buttons and fields of a form that was not submitted are not sent at all; reading them directly would cause "Undefined array key" warnings.

Answer : Because an attacker can add text to the URL path that is reflected in the page; htmlspecialchars() prevents this from being interpreted as HTML/JavaScript.

Answer : No. The posted values are not part of the URL, so a bookmark would load the page without them.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which array holds values sent by a form with method="post"?

Show Answer

Correct Answer : B. $_POST
POST data is available in $_POST.

Q2. Which method displays form data in the browser's address bar?

Show Answer

Correct Answer : C. GET
GET appends the data to the URL.

Q3. $_REQUEST contains the contents of:

Show Answer

Correct Answer : B. $_GET, $_POST and $_COOKIE
$_REQUEST merges GET, POST and COOKIE data.

Q4. Which function protects output against XSS?

Show Answer

Correct Answer : B. htmlspecialchars()
It converts special HTML characters into entities.

Q5. To receive several checked checkboxes as an array, the field name should be:

Show Answer

Correct Answer : B. hobby[]
The [] suffix makes PHP collect the values into an array.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – Dealing with Forms. https://www.php.net/manual/en/tutorial.forms.php
  2. The PHP Group. (n.d.). PHP Manual – $_POST. https://www.php.net/manual/en/reserved.variables.post.php
  3. The PHP Group. (n.d.). PHP Manual – $_GET. https://www.php.net/manual/en/reserved.variables.get.php
  4. The PHP Group. (n.d.). PHP Manual – htmlspecialchars. https://www.php.net/manual/en/function.htmlspecialchars.php
  5. OWASP Foundation. (n.d.). Cross Site Scripting (XSS). https://owasp.org/www-community/attacks/xss/