ICT 選修乙 · 第三章ICT Elective B · Chapter 3

接收客戶端輸入Receiving Client Input

(PHP II)

學習如何使用 HTML 表單、HTTP 請求方法、PHP Superglobals、伺服器端驗證及 Cookies 建立互動式網頁應用程式。Learn how to use HTML forms, HTTP request methods, PHP Superglobals, server-side validation, and Cookies to build interactive web applications.

使用 HTML 表單元素建立客戶端介面Build client interfaces with HTML form elements
了解 GET 與 POST 請求方法的分別Understand GET vs POST request methods
透過 PHP 實作伺服器端資料驗證Implement server-side data validation via PHP
了解 Cookies 在網頁開發中的應用Understand how Cookies are used in web development

本章內容Chapter Overview

點擊卡片快速跳轉到對應章節Click a card to jump to that section

3.1 / 3.2
簡介與 HTML 輸入類型Intro & HTML Input Types
3.2
建立 HTML 表單Building HTML Forms
3.3
GET vs POSTGET vs POST
3.4
PHP SuperglobalsPHP Superglobals
3.5
伺服器端驗證Server-Side Validation
3.6
Cookies
練習Practice
互動測驗 (12題)Interactive Quiz (12 Qs)
練習Practice
閃卡複習 (20張)Flashcard Review (20)
練習Practice
歷屆試題 (6題)Past Questions (6)

簡介 & HTML 輸入類型Introduction & HTML Input Types

接收使用者輸入Receiving User Input

大多數網頁依賴使用者輸入來提供個人化體驗。當你在文字框輸入或點擊按鈕時,你正在向伺服器提交資料。伺服器處理資料後,回傳一個 HTML 檔案給瀏覽器。

在本章,我們將學習伺服器如何透過 HTML 表單接收使用者輸入,並了解 GET 和 POST 兩種請求方法,以及如何透過 PHP 的 Superglobals 回應不同的請求。

Most web pages rely on users' input to provide a personalised experience. When you type in a textbox or click a button, you are submitting data to a server. The server processes the data and returns an HTML file to the browser.

In this chapter, we learn how a server receives user input through HTML forms, and understand the GET and POST request methods, and how to respond through PHP Superglobals.

HTML 輸入類型HTML Input Types

Text Field

最基本的輸入類型,讓使用者輸入文字。

The most basic input type; allows users to enter text.

<input type="text" name="nickname">

Password Field

輸入時遮蔽字元,適用於密碼等敏感資料。

Obscures the user's input on screen; used for sensitive data like passwords.

<input type="password" name="pw">

Date Field

專門用於輸入日期,提供日期選擇器,減少輸入錯誤。

Specifically for date input; provides a date picker to reduce errors.

<input type="date" name="bday">

Dropdown

提供預設選項,使用者只能選擇其中一項(預設)。

Provides predefined choices; by default, only one option can be selected.

<select name="region">
 <option value="HK">HK</option>
</select>

Checkbox

允許使用者為同一欄位選擇多個值。所有同組核取方塊使用相同的 name[]。

Allows users to submit multiple values for one field. All checkboxes in the same group share the same name[].

<input type="checkbox" name="lang[]" value="en">

Submit Button

點擊後瀏覽器將表單資料傳送到 action 屬性指定的位置。

When clicked, the browser sends the form's data to the location specified in the action attribute.

<input type="submit" name="submit">
重要:Important: 每個 <input> 元素都必須定義 name 屬性,它作為表單資料的索引。required 屬性可強制使用者填寫欄位(客戶端驗證)。 Every <input> element must have a name attribute, serving as the index for form data. The required attribute forces users to fill in a field (client-side validation).

建立 HTML 表單Building HTML Forms

<form> 標籤The <form> Tag

<form> ... </form> 標籤對定義一個 HTML 表單。所有輸入元素必須放在此標籤對之間。

兩個重要屬性:

  • action:指定表單資料要傳送到的位置(通常是 PHP 檔案)
  • method:指定使用 GET 還是 POST 方法傳送資料

The <form> ... </form> tag pair defines an HTML form. All input elements must be placed within this tag pair.

Two important attributes:

  • action: specifies where the form data should be sent (usually a PHP file)
  • method: specifies whether GET or POST should be used to send the data
<form action="process.php" method="POST">
  Name: <input type="text" name="name" required> <br>
  Gender: <select name="gender">
    <option value="m">Male</option>
    <option value="f">Female</option>
  </select> <br>
  <input type="checkbox" name="lang[]" value="canto"> Cantonese
  <input type="checkbox" name="lang[]" value="eng"> English <br>
  <input type="submit" name="submit">
</form>
若 action 設為空字串 "",瀏覽器會將請求傳送到同一個 URL,適合在同一頁面顯示處理結果。If action is set to an empty string "", the browser sends the request to the same URL, useful for displaying results on the same page.

提交 HTML 表單:GET vs POSTSubmitting HTML Forms: GET vs POST

表單提交的三個步驟Three Steps of Form Submission

步驟 1:整理資料Step 1: Organise Data

瀏覽器將每個 <input> 的 name 作為索引,使用者輸入的資料作為值,整理成索引-值對。

The browser organises each <input>'s name as the index and the user-inputted data as the value, forming index-value pairs.

步驟 2:準備 HTTP 請求Step 2: Prepare HTTP Request

瀏覽器根據 action(請求 URL)和 method(GET 或 POST)準備 HTTP 請求。

The browser prepares an HTTP request using the action (Request URL) and method (GET or POST).

步驟 3:加入表單資料Step 3: Add Form Data

GET → 資料編碼為查詢字串,附加在請求 URL 後。
POST → 資料放入請求主體,不顯示於 URL。

GET → data encoded as a query string appended to the request URL.
POST → data placed in the request body, not visible in the URL.

GET vs POST 詳細比較Detailed Comparison: GET vs POST

比較項目AspectGETPOST
目的Desired Action從伺服器取得特定資源Fetch a specific resource from the server向伺服器提交資訊以執行特定操作Submit information to perform a specific action
資料位置Data Location編碼為查詢字串,在 URL 中可見Encoded as query string in the URL (visible)放在請求主體,使用者不可見Contained in the request body (not visible)
書籤/歷史Bookmarked/History可被書籤和瀏覽歷史記錄Can be bookmarked and saved in browsing history不會被儲存或書籤Not saved or bookmarked
大小限制Length Limit受 URL 長度限制(約 2KB),只允許文字資料Limited by URL length (~2KB); text data only無大小限制,可包含二進位資料No size limit; binary data allowed
快取Caching回應可被快取Responses can be cached回應通常不被快取Responses are not cached in general
使用場景Use Case搜尋、篩選(不改變伺服器狀態)Search, filter (does not change server state)登入、購買、新增記錄(改變伺服器狀態)Login, purchase, add records (changes server state)
安全提示:Security Note: 傳送密碼等敏感資料時,必須使用 POST,因為 GET 的查詢字串在網址列可見,可能洩露敏感資訊。 When sending sensitive data like passwords, always use POST, as GET's query string is visible in the address bar.

查詢字串範例 (GET)Query String Example (GET)

# Form data: name=Andy, height=179, weight=81.3, region=HK
# GET request URL:
https://mysite.net/resultBMI.php?name=Andy&height=179&weight=81.3&region=HK

# POST request body (not in URL):
name = Andy | height = 179 | weight = 81.3 | region = HK

PHP Superglobals:$_POST 與 $_GETPHP Superglobals: $_POST and $_GET

當伺服器收到 HTTP 請求後,PHP 會自動將請求資料整理到 Superglobal 關聯陣列中,PHP 檔案可以直接存取這些值。

When the server receives an HTTP request, PHP automatically gathers the request data into Superglobal associative arrays, which the PHP file can access directly.

$_POST

收到 POST 請求時,請求主體的所有資料被整理到 $_POST 關聯陣列。

When a POST request is received, all data in the request body is gathered into the $_POST associative array.

indexvalue
"name""Andy"
"height""179"
"weight""81.2"
"submit""submit"
$name = $_POST["name"];
if($_POST["marks"] >= 80){
 $grade = "A";
}

$_GET

收到 GET 請求時,查詢字串的所有資料被整理到 $_GET 關聯陣列。

When a GET request is received, all data in the query string is gathered into the $_GET associative array.

indexvalue
"year""2022"
"subject""english"
"subpaper""3"
$subject = $_GET["subject"];
if($_GET["year"] < 2012){
 echo "No past paper before 2012!";
}
isset() & empty()

存取 Superglobals 前,應先用 isset() 或 empty() 檢查索引是否存在,避免 runtime 錯誤。

  • isset($var):若變數存在則回傳 true(不論其值)
  • empty($var):若變數不存在或為空值則回傳 true

Before accessing Superglobals, use isset() or empty() to check if an index exists, to avoid runtime errors.

  • isset($var): returns true if the variable exists (regardless of value)
  • empty($var): returns true if the variable does NOT exist or is empty

實例:BMI 計算器 (resultBMI.php)Example: BMI Calculator (resultBMI.php)

$$BMI = \frac{weight\ (KG)}{height\ (m)^2}$$
<?php
$valid = true;
// Presence check for name
if(empty($_POST["name"])){ $valid = false; }
// Presence + Range check for height (0-250)
if(empty($_POST["height"])){ $valid = false; }
elseif($_POST["height"] < 0 || $_POST["height"] > 250){ $valid = false; }
if($valid){
  $bmi = $_POST["weight"] / (($_POST["height"] / 100) ** 2);
  echo "Hi {$_POST['name']}, your BMI is {$bmi}.";
} else { echo "Invalid data entered!"; }
?>

伺服器端資料驗證Server-Side Data Validation

客戶端驗證 Client-Side Validation

由瀏覽器在資料傳送前執行。通常透過 HTML 屬性(如 required、min、max)或 JavaScript 實作。

優點:減少伺服器負擔,節省使用者時間

缺點:若 JS 被停用,可能失效;可被繞過

Performed by the browser before data is sent. Usually via HTML attributes or JavaScript.

Pros: Reduces server load, saves time for the user

Cons: May fail if JS is disabled; can be bypassed

伺服器端驗證 Server-Side Validation

由伺服器在收到資料後執行。通常透過 PHP 等伺服器端語言實作。

優點:更可靠,無法被繞過;可執行只有伺服器才能做的驗證(如檢查用戶名是否已被使用)

Performed by the server after receiving data. Usually via PHP or other server-side languages.

Pros: More reliable, cannot be bypassed; can perform server-only checks (e.g. check if username is taken)

客戶端和伺服器端驗證並不互斥,實際開發中應同時使用兩者,以確保資料安全和良好的使用者體驗。Client-side and server-side validation are not mutually exclusive; in practice, both should be used to ensure data security and a good user experience.

PHP 常用資料驗證函數Commonly Used PHP Validation Functions

驗證類型Validation TypePHP 函數PHP Function說明Description範例Example
存在性檢查Presence Checkempty()若變數不存在或為空則回傳 trueReturns true if variable does not exist or is emptyif(empty($_POST["name"]))
固定值檢查Fixed Value Checkin_array()若值存在於陣列中則回傳 trueReturns true if value exists in the arrayin_array($val, ["A","B","C"])
類型檢查Type Checkis_numeric()若為數字或數字字串則回傳 trueReturns true if value is a number or numeric stringis_numeric($_POST["age"])
長度檢查Length Checkstrlen()回傳字串的字元數Returns the number of characters in a stringstrlen($_POST["uid"]) > 20
格式檢查Format Checkstrpos()回傳子字串的位置;找不到則回傳 falseReturns position of substring; false if not found!strpos($_POST["email"],"@")

Cookies

Cookie 是網站儲存在客戶端瀏覽器上的一個小型文字檔案,包含鍵值對(key-value pairs),並通常與特定域名和到期日相關聯。透過重複使用和操控儲存在客戶端的資料,可以為每個使用者提供一定程度的個人化體驗。

A Cookie is a small text file stored by a website on the client's browser. It contains key-value pairs and is usually associated with a specific domain and expiration date. By reusing and manipulating data stored on the client side, it is possible to enable personalised experience for each user.

Cookie 的運作流程How Cookies Work

// PHP: Accessing a Cookie value
echo $_COOKIE["university"]; // e.g. outputs "HKU"

Cookie 的用途 Cookie Benefits

  • 儲存語言偏好設定
  • Save language preferences
  • 記錄上次搜尋記錄
  • Store last search records
  • 記錄購物車內容
  • Remember shopping cart items
  • 儲存篩選條件
  • Store filter criteria
  • 使用者行為分析
  • User behaviour analytics

Cookie 的風險 Cookie Risks

  • Cookie 值可被使用者或瀏覽器擴充功能修改
  • Cookie values can be altered by the user or browser extensions
  • Cookie 可能被刪除或停用
  • Cookies may be deleted or disabled
  • 大小限制(通常 4KB)
  • Size limit (typically 4KB)
  • 不應儲存敏感資料(如密碼、信用卡號)
  • Should not store sensitive data (passwords, credit card numbers)

知識測驗Knowledge Quiz

共 12 題,涵蓋本章所有重點。完成後查看成績。12 questions covering all key topics. Check your score when done.

1. 以下哪個 HTML 屬性用於定義表單資料傳送到的位置?1. Which HTML attribute specifies where form data should be sent?

2. 使用 GET 方法提交表單時,表單資料如何傳送?2. When a form is submitted using GET method, how is the form data transmitted?

3. 以下哪種情況應使用 POST 方法而非 GET?3. In which scenario should POST be used instead of GET?

4. 在 PHP 中,哪個 Superglobal 用於存取 POST 請求中的表單資料?4. Which PHP Superglobal is used to access form data from a POST request?

5. PHP 函數 empty() 的作用是?5. What does the PHP function empty() do?

6. 以下哪個 input type 會在輸入時隱藏字元?6. Which input type obscures the user's input when displayed on screen?

7. 核取方塊的 name 屬性應如何設定才能讓伺服器接收多個選擇?7. How should the name attribute of checkboxes be set so the server can receive multiple selections?

8. 下列哪項是客戶端驗證的缺點?8. Which of the following is a disadvantage of client-side validation?

9. 哪個 PHP 函數用於檢查一個值是否為數字或數字字串?9. Which PHP function checks if a value is a number or numeric string?

10. Cookie 儲存在哪裡?10. Where are Cookies stored?

11. PHP 透過哪個 Superglobal 存取客戶端的 Cookie 值?11. Which PHP Superglobal is used to access Cookie values from the client?

12. 以下哪項資料不應儲存在 Cookie 中?12. Which of the following data should NOT be stored in a Cookie?

關鍵詞彙閃卡Key Terms Flashcards

點擊卡片翻轉查看解釋,共 20 張。Click a card to flip and see the definition. 20 cards total.

HTML Form
HTML 表單Web element
點擊翻轉Click to flip
一個包含各種輸入元素的網頁元件,讓使用者輸入資料並提交到伺服器。A web element containing various input fields that allows users to enter and submit data to a server.
action attribute
action 屬性<form> attribute
點擊翻轉Click to flip
定義 HTTP 請求應傳送到的位置(通常是伺服器上的 PHP 檔案)。Defines the location to which the HTTP request should be sent (usually a PHP file on the server).
Query String
查詢字串GET method
點擊翻轉Click to flip
使用 GET 方法時,表單資料編碼後附加在請求 URL 後的部分,以 ? 開始,各對以 & 分隔。When using GET, the part of the request URL that encodes form data, starting with ? and separating pairs with &.
Request Body
請求主體POST method
點擊翻轉Click to flip
使用 POST 方法時,表單資料放在 HTTP 請求主體中,不在 URL 中可見,無大小限制。When using POST, form data is placed in the HTTP request body — not visible in the URL and has no size limit.
$_POST
PHP SuperglobalPHP Superglobal
點擊翻轉Click to flip
PHP Superglobal 關聯陣列,收到 POST 請求時,包含請求主體中的所有表單資料。PHP Superglobal associative array containing all form data from the request body when a POST request is received.
$_GET
PHP SuperglobalPHP Superglobal
點擊翻轉Click to flip
PHP Superglobal 關聯陣列,收到 GET 請求時,包含查詢字串中的所有資料。PHP Superglobal associative array containing all data from the query string when a GET request is received.
$_COOKIE
PHP SuperglobalPHP Superglobal
點擊翻轉Click to flip
PHP Superglobal,讓伺服器端腳本存取客戶端瀏覽器儲存的 Cookie 值。PHP Superglobal that allows server-side scripts to access Cookie values stored in the client's browser.
isset()
PHP 函數PHP function
點擊翻轉Click to flip
若變數在 runtime 中存在(不論其值),則回傳 true。常用於存取 Superglobal 前檢查索引是否存在。Returns true if the variable exists at runtime (regardless of value). Used to check if an index exists in a Superglobal before accessing it.
empty()
PHP 函數PHP function
點擊翻轉Click to flip
若變數在 runtime 中不存在或為空值則回傳 true。常用於存在性檢查(Presence Check)。Returns true if the variable does NOT exist at runtime or is empty. Commonly used for Presence Checks.
Presence Check
存在性檢查Validation type
點擊翻轉Click to flip
驗證某個必填欄位是否已被填寫(不為空),通常使用 empty() 實作。Validates that a required field has been filled in (is not empty). Usually implemented using empty().
Range Check
範圍檢查Validation type
點擊翻轉Click to flip
驗證數值是否在合理範圍內,例如身高必須在 0 至 250 之間。Validates that a numeric value is within a reasonable range, e.g. height must be between 0 and 250.
Server-Side Validation
伺服器端驗證Validation
點擊翻轉Click to flip
由伺服器在收到資料後執行的驗證,使用 PHP 等伺服器端語言,更可靠且不能被繞過。Validation performed by the server after receiving data. Uses PHP, is more reliable, and cannot be bypassed by the client.
Client-Side Validation
客戶端驗證Validation
點擊翻轉Click to flip
由瀏覽器在資料傳送前執行的驗證,通常透過 HTML 屬性或 JavaScript。可減少伺服器負擔,但可能被繞過。Validation performed by the browser before data is sent, usually via HTML attributes or JavaScript. Reduces server load but can be bypassed.
Cookie
網頁開發概念Web concept
點擊翻轉Click to flip
網站儲存在客戶端瀏覽器的小型文字檔案,包含鍵值對,用於記住使用者偏好和狀態。A small text file stored by a website on the client's browser, containing key-value pairs used to remember user preferences and state.
set-cookie header
HTTP 標頭HTTP header
點擊翻轉Click to flip
伺服器在 HTTP 回應中附加的標頭,指示瀏覽器建立一個具有指定索引和值的 Cookie。A header attached to an HTTP response by the server, instructing the browser to create a Cookie with a specified index and value.
is_numeric()
PHP 函數PHP function
點擊翻轉Click to flip
若給定的變數是數字或數字字串則回傳 true,常用於類型檢查(Type Check)。Returns true if the given variable is a number or a numeric string. Used for Type Checks.
in_array()
PHP 函數PHP function
點擊翻轉Click to flip
若給定值存在於指定陣列中則回傳 true,常用於固定值檢查(Fixed Value Check)。Returns true if the given value exists in the specified array. Used for Fixed Value Checks.
strpos()
PHP 函數PHP function
點擊翻轉Click to flip
回傳子字串在字串中第一次出現的位置;找不到則回傳 false。常用於格式檢查(如驗證電子郵件是否包含 "@")。Returns the position of the first occurrence of a substring. Returns false if not found. Used for Format Checks, e.g. verifying an email contains "@".
name attribute
<input> 屬性<input> attribute
點擊翻轉Click to flip
每個 <input> 元素必須定義的屬性,作為表單資料的索引,伺服器透過此索引存取對應的值。A required attribute for every <input> element; serves as the index for form data, used by the server to access the corresponding value.
Flag Variable ($valid)
標誌變數PHP concept
點擊翻轉Click to flip
在伺服器端驗證中使用的布林變數(如 $valid),初始為 true,若任何驗證失敗則設為 false,最後決定是否執行後續操作。A boolean variable (e.g. $valid) used in server-side validation. Initialised to true; set to false if any validation fails, determining whether to proceed with processing.

練習題目Practice Questions

根據本章重點整理的練習題,附參考答案。Practice questions based on chapter key topics, with reference answers.

基礎Basic表單基礎Forms

在 HTML 表單中,為什麼每個 <input> 元素都必須定義 name 屬性?請解釋其作用。(2 分)

In an HTML form, why must every <input> element have a name attribute defined? Explain its role. (2 marks)

參考答案:

表單資料透過 HTTP 請求以索引-值對的形式傳送。每個 <input> 的 name 屬性用作該欄位的索引,使用者輸入的資料則是對應的值。若沒有定義 name 屬性,伺服器將無法識別和存取該欄位的資料。

Reference Answer:

Form data is sent via HTTP requests as index-value pairs. The name attribute of each <input> serves as the index for that field, while the user-inputted data is the value. Without a name attribute, the server cannot identify and access the field's data.

基礎BasicGET / POST

說明 GET 和 POST 請求方法在「資料如何包含在 HTTP 請求中」這一方面的兩個分別。(2 分)

State TWO differences between GET and POST methods regarding how data is contained in an HTTP request. (2 marks)

參考答案(任答兩點):

  • GET 的資料編碼為查詢字串,是請求 URL 的一部分;POST 的資料放在請求主體中。
  • GET 的資料在網址列可見;POST 的資料對使用者不可見。
  • GET 的資料大小受 URL 長度限制(約 2KB);POST 無大小限制。
  • GET 的請求可被書籤或瀏覽歷史記錄;POST 不會被儲存。

Reference Answer (any two):

  • GET data is encoded as a query string forming part of the request URL; POST data is in the request body.
  • GET data is visible in the address bar; POST data is not visible to the user.
  • GET data is limited by URL length (~2KB); POST has no size limit.
  • GET requests can be bookmarked or saved in browsing history; POST requests are not saved.
中等MediumPHP Validation

Joyce 正在開發一個問卷網頁,有一個電子郵件欄位。請寫出 PHP 代碼,對電子郵件欄位進行以下驗證,若驗證失敗則將 $valid 設為 false:存在性檢查 + 格式檢查(必須包含 "@" 符號)。(2 分)

Joyce is developing a questionnaire web page with an email field. Write PHP code to perform the following validation on the email field, setting $valid to false if validation fails: Presence check + Format check (email must contain "@"). (2 marks)

// Presence check
if(empty($_POST["email"])){ $valid = False; }
// Format check: must contain "@"
elseif(!strpos($_POST["email"], "@")){ $valid = False; }
中等MediumCookies

Leon 正在開發一個大學設施搜尋網頁應用程式。
(a) 雖然 Cookie 完全儲存在客戶端瀏覽器,但伺服器端腳本仍可使用 Cookie 中儲存的值。參考 Cookie 如何透過 HTTP 請求和回應傳輸,解釋為何這是可能的。(2 分)
(b) 描述兩種可以使用 Cookie 來改善使用者體驗的方法。(2 分)

Leon is developing a web application for students to search for university facilities.
(a) Despite Cookies being stored entirely on the client's browser, server-side scripts can use values stored in a Cookie. Explain why this is possible with reference to how Cookies are transmitted through HTTP requests and responses. (2 marks)
(b) Describe TWO ways Cookies can be used to improve the user experience. (2 marks)

(a) 由某域名設定的 Cookie 會在每次向該域名發送 HTTP 請求時一併傳送到伺服器。因此,伺服器端腳本可以透過 HTTP 請求存取 Cookie 中儲存的值。伺服器也可以透過在 HTTP 回應中附加 set-cookie 標頭來設定新的 Cookie。

(b) 任答兩點:

  • 儲存上次的搜尋結果,讓使用者下次訪問時快速取得
  • 儲存使用者的搜尋偏好(如設施類型)
  • 儲存使用者的語言偏好

(a) Cookies set by a domain are sent to the server in every HTTP request made to that domain. Therefore, server-side scripts can access values stored in Cookies through the HTTP request. The server can also set new Cookies by attaching a set-cookie header in the HTTP response.

(b) Any two:

  • Store previous search results for faster access next time
  • Store the user's search preferences (e.g. facility type)
  • Store the user's preferred language
困難HardGPA / PHP

Adrian 正在開發一個計算畢業 GPA 的網頁應用程式。畢業 GPA 公式:

$$gGPA = \frac{GPA_1 + GPA_2 + (GPA_3 \times 1.5) + (GPA_4 \times 2)}{1 + 1 + 1.5 + 2}$$

請完成 processGPA.php:(i) 輸出學生姓名 (ii) 輸出所屬學院 (iii) 計算畢業 GPA (iv) 輸出畢業 GPA。(4 分)

Adrian is developing a web application to calculate a student's graduating GPA. The formula:

$$gGPA = \frac{GPA_1 + GPA_2 + (GPA_3 \times 1.5) + (GPA_4 \times 2)}{1 + 1 + 1.5 + 2}$$

Complete processGPA.php: (i) Output student's name (ii) Output faculty (iii) Calculate graduating GPA (iv) Output graduating GPA. (4 marks)

<?php
// (i) Output the student's name
echo "Student name: {$_POST['name']}";
// (ii) Output the student's home faculty
echo "Faculty: {$_POST['faculty']}";
// (iii) Calculate the graduating GPA
$gGPA = ($_POST["gpa_1"] + $_POST["gpa_2"] + ($_POST["gpa_3"] * 1.5) + ($_POST["gpa_4"] * 2)) / (1 + 1 + 1.5 + 2);
// (iv) Output the graduating GPA
echo "Your graduating GPA is {$gGPA}";
?>
困難Hard綜合應用Application

一間電影院 iLoveMovies 正在開發一個網站供顧客搜尋電影及購買門票。(7 分)
(a) 搜尋電影時,顧客需要輸入:一個電影院分店、一個日期、一個類型。請說明應使用哪三種不同的 HTML 表單元素。(3 分)
(b) 針對搜尋電影和購票功能,分別建議應使用 GET 還是 POST 方法,並解釋原因。(2 分)
(c) 說明對此網站使用 GET 方法的兩個好處。(2 分)

A cinema iLoveMovies is developing a website for customers to search for movies and purchase tickets. (7 marks)
(a) To search for movies, users input: one cinema branch, one date, one genre. Suggest THREE different HTML form elements. (3 marks)
(b) Suggest which HTTP method (GET or POST) should be used for search and for purchasing tickets respectively, with explanation. (2 marks)
(c) Suggest TWO benefits of using GET method for this website. (2 marks)

(a) 電影院分店:下拉選單(<select>);日期:日期輸入框(<input type="date">);類型:下拉選單或核取方塊

(b) 搜尋電影:GET,因為此請求是從伺服器取得特定資源,不會改變伺服器狀態,搜尋結果可被書籤。購票:POST,因為此請求會在伺服器資料庫新增一筆記錄,會改變伺服器狀態。

(c) 任答兩點:

  • 搜尋結果可被書籤,讓使用者下次直接存取相同的搜尋結果
  • GET 的回應可被快取,減少伺服器負擔和等待時間

(a) Cinema branch: Dropdown (<select>); Date: Date input (<input type="date">); Genre: Dropdown or Checkbox

(b) Search for movies: GET, as this retrieves a specific resource without changing server state; results can be bookmarked. Purchase ticket: POST, as this creates a new record in the server's database, effecting a change on the server's state.

(c) Any two:

  • Search results can be bookmarked, allowing users to directly access the same search results next time
  • Responses to GET requests can be cached, reducing server load and wait times