【學習筆記】session機制實現PHP購物車
使用到session的頁面必須要有session啟動函數session_start();清空系統中session可以用session_destroy();函數。
在php.ini檔案中關於session的配置:session.save_path定義了存放session 的路徑;session.name定義了sessionID的名稱。
下面是練習的例子,列出代碼。
index.html頁面:
商品分類列表運動器材
辦公用品
煙酒副食
查看購物車
檔案a.php頁面代碼:
購物街請選擇商品
檔案b.php頁面代碼:
購物街請選擇商品
檔案c.php頁面代碼:
購物街請選擇商品
index.php資料處理頁面:
$value)statement*/if(isset($_POST['d'])){//是否從購物車管理介面提交過來的foreach($_POST['d'] as $c){//如果是,則將提交過來的商品序號從購物車數組中刪除unset($_SESSION['cart'][$c]);}}?>運動器材
辦公用品
煙酒副食
查看購物車
購物車管理頁面cart.php,這裡主要實現刪除商品、撤銷購物頁面:
這裡要注意php中form表單中enctype屬性的設定。
form表單中的enctype屬性指定將資料發回到伺服器時瀏覽器使用的編碼類別型。
下面是取值說明:
multipart/form-data: 表單資料被編碼為一條訊息,頁上的每個控制項對應訊息中的一個部分,不對字元編碼。當使用有檔案上傳控制項的表單時,該值是必需的。。
application/x-www-form-urlencoded: 表單資料被編碼為名稱/值對。這是標準的編碼格式。在發送前對所有字元進行編碼(預設)。
text/plain: 表單資料以純文字形式進行編碼,其中不含任何控制項或格式字元。將空格轉換為 "+" 符號,但不編碼特殊字元。抓包可見資料形式。
說明:
1)如果表單中有檔案要上傳,表單中form標籤必須設定enctype="multipart/form-data"來確保匿名上傳檔案的MIME編碼。預設情況下,表單的編碼格式是 application/x-www-form-urlencoded,不能用於檔案上傳;
2)進行session處理時,如果將表單設定enctype="text/plain",則通過$_POST,$_GET,$_REQUEST等是無法取到值的。這點一定要小心!!!
對於三種類型的進一步解釋,實質參考如下:
enctype defines how the data should be formatted before sending. the two correct formats are application/x-www-form-urlencoded (which essentially sends things as key=valye&anotherkey=anothervalue, with http headers) and multipart/form-data (which splits each key up into a distinct section of data). text/plain means nothing should be done - its behaviour is essentially undefined between browsers, and was only ever used for automated email forms in the days before spam. use application/x-www-form-urlencoded for text forms (or leave this to use the default setting) and multipart/form-data for file attachment uploads
text/plain:
Content-Type: text/plain================================================================================foo=barbaz=The first line.The second line.
application/x-www-form-urlencoded:
Content-Type: application/x-www-form-urlencoded================================================================================foo=bar&baz=The+first+line.%0D%0AThe+second+line.%0D%0A
multipart/form-data:
Content-Type: multipart/form-data; boundary=---------------------------314911788813839================================================================================-----------------------------314911788813839Content-Disposition: form-data; name="foo"bar-----------------------------314911788813839Content-Disposition: form-data; name="baz"The first line.The second line.-----------------------------314911788813839--
you can see how the first one is useful for passing values UNCHECKED directly into an email program (e.g. if your form uses a mailto: address, so it uses your visitor's email program to send) but is largely useless for programmatic access to fields. only the bottom 2 examples are valid for actual form-based form data