GET和POST兩種方法都是將數據送到服務器,但你該用哪一種呢?
HTTP標准包含這兩種方法是為了達到不同的目的。POST用於創建資源,資源的內容會被編入HTTP請示的內容中。例如,處理訂貨表單、在數據庫中加入新數據行等。
當請求無副作用時(如進行搜索),便可使用GET方法;當請求有副作用時(如添加數據行),則用POST方法。一個比較實際的問題是:GET方法可能會產生很長的URL,或許會超過某些瀏覽器與服務器對URL長度的限制。
若符合下列任一情況,則用POST方法:
* 請求的結果有持續性的副作用,例如,數據庫內添加新的數據行。
* 若使用GET方法,則表單上收集的數據可能讓URL過長。
* 要傳送的數據不是采用7位的ASCII編碼。
若符合下列任一情況,則用GET方法:
* 請求是為了查找資源,HTML表單數據僅用來幫助搜索。
* 請求結果無持續性的副作用。
* 收集的數據及HTML表單內的輸入字段名稱的總長不超過1024個字符。
以上內容摘自《Web Database Application with PHP and MySQL, 2nd Edition》一書,中文版《PHP & MySQL Web數據庫應用開發指南》。英文原文內容如下:
GET versus POST
Both the GET and POST methods send data to the server, but which method should you use?
The HTTP standard includes the two methods to achieve different goals. The POST method was intended to create a resource. The contents of the resource would be encoded into the body of the HTTP request. For example, an order form might be processed and a new row in a database created.
The GET method is used when a request has no side effects (such as performing a search) and the POST method is used when a request has side effects (such as adding a new row to a database). A more practical issue is that the GET method may result in long URLs, and may even exceed some browser and server limits on URL length.
Use the POST method if any of the following are true:
* The result of the request has persistent side effects such as adding a new database row.
* The data collected on the form is likely to result in a long URL if you used the GET method.
* The data to be sent is in any encoding other than seven-bit ASCII.
Use the GET method if all the following are true:
* The request is to find a resource, and HTML form data is used to help that search.
* The result of the request has no persistent side effects.
* The data collected and the input field names in a HTML form are in total less than 1,024 characters in size.