(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.
點擊卡片快速跳轉到對應章節Click a card to jump to that section
大多數網頁依賴使用者輸入來提供個人化體驗。當你在文字框輸入或點擊按鈕時,你正在向伺服器提交資料。伺服器處理資料後,回傳一個 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.
最基本的輸入類型,讓使用者輸入文字。
The most basic input type; allows users to enter text.
輸入時遮蔽字元,適用於密碼等敏感資料。
Obscures the user's input on screen; used for sensitive data like passwords.
專門用於輸入日期,提供日期選擇器,減少輸入錯誤。
Specifically for date input; provides a date picker to reduce errors.
提供預設選項,使用者只能選擇其中一項(預設)。
Provides predefined choices; by default, only one option can be selected.
允許使用者為同一欄位選擇多個值。所有同組核取方塊使用相同的 name[]。
Allows users to submit multiple values for one field. All checkboxes in the same group share the same name[].
點擊後瀏覽器將表單資料傳送到 action 屬性指定的位置。
When clicked, the browser sends the form's data to the location specified in the action attribute.
<form> ... </form> 標籤對定義一個 HTML 表單。所有輸入元素必須放在此標籤對之間。
兩個重要屬性:
The <form> ... </form> tag pair defines an HTML form. All input elements must be placed within this tag pair.
Two important attributes:
瀏覽器將每個 <input> 的 name 作為索引,使用者輸入的資料作為值,整理成索引-值對。
The browser organises each <input>'s name as the index and the user-inputted data as the value, forming index-value pairs.
瀏覽器根據 action(請求 URL)和 method(GET 或 POST)準備 HTTP 請求。
The browser prepares an HTTP request using the action (Request URL) and method (GET or POST).
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.
| 比較項目Aspect | GET | POST |
|---|---|---|
| 目的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) |
當伺服器收到 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 關聯陣列。
When a POST request is received, all data in the request body is gathered into the $_POST associative array.
| index | value |
|---|---|
| "name" | "Andy" |
| "height" | "179" |
| "weight" | "81.2" |
| "submit" | "submit" |
收到 GET 請求時,查詢字串的所有資料被整理到 $_GET 關聯陣列。
When a GET request is received, all data in the query string is gathered into the $_GET associative array.
| index | value |
|---|---|
| "year" | "2022" |
| "subject" | "english" |
| "subpaper" | "3" |
存取 Superglobals 前,應先用 isset() 或 empty() 檢查索引是否存在,避免 runtime 錯誤。
Before accessing Superglobals, use isset() or empty() to check if an index exists, to avoid runtime errors.
由瀏覽器在資料傳送前執行。通常透過 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
由伺服器在收到資料後執行。通常透過 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)
| 驗證類型Validation Type | PHP 函數PHP Function | 說明Description | 範例Example |
|---|---|---|---|
| 存在性檢查Presence Check | empty() | 若變數不存在或為空則回傳 trueReturns true if variable does not exist or is empty | if(empty($_POST["name"])) |
| 固定值檢查Fixed Value Check | in_array() | 若值存在於陣列中則回傳 trueReturns true if value exists in the array | in_array($val, ["A","B","C"]) |
| 類型檢查Type Check | is_numeric() | 若為數字或數字字串則回傳 trueReturns true if value is a number or numeric string | is_numeric($_POST["age"]) |
| 長度檢查Length Check | strlen() | 回傳字串的字元數Returns the number of characters in a string | strlen($_POST["uid"]) > 20 |
| 格式檢查Format Check | strpos() | 回傳子字串的位置;找不到則回傳 falseReturns position of substring; false if not found | !strpos($_POST["email"],"@") |
共 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?
點擊卡片翻轉查看解釋,共 20 張。Click a card to flip and see the definition. 20 cards total.
根據本章重點整理的練習題,附參考答案。Practice questions based on chapter key topics, with reference answers.
在 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.
說明 GET 和 POST 請求方法在「資料如何包含在 HTTP 請求中」這一方面的兩個分別。(2 分)
State TWO differences between GET and POST methods regarding how data is contained in an HTTP request. (2 marks)
參考答案(任答兩點):
Reference Answer (any two):
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)
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:
Adrian 正在開發一個計算畢業 GPA 的網頁應用程式。畢業 GPA 公式:
請完成 processGPA.php:(i) 輸出學生姓名 (ii) 輸出所屬學院 (iii) 計算畢業 GPA (iv) 輸出畢業 GPA。(4 分)
Adrian is developing a web application to calculate a student's graduating GPA. The formula:
Complete processGPA.php: (i) Output student's name (ii) Output faculty (iii) Calculate graduating GPA (iv) Output graduating GPA. (4 marks)
一間電影院 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) 任答兩點:
(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: