|
ここにある情報はかなり古くなっており、正しくなくなっている可能性があります。掲載しているサンプルコードiなどは、最新のPHPでは動作しない、もしくは、別途設定・調整が必要になるかも知れません。情報を鵜呑みにせず、あなたの手を動かして、あなたの目で確認してください。
セッションIDの出力には、XSS対策のためstrip_tags関数を通したものを出力することが推奨されています。ただし、HTMLタグの内側にその値が含まれる場合、htmlspecialchars関数を使用する必要があります。
これもよくあるネタですよね。今回はPHP4のSession管理機能を使ってカートを保持させています。カートのソース自体は、マニュアルに載っているものを参考にしました。ショッピングカートの基本的な流れはこんな感じと思います。後は、購入処理や購入後のカートを消す等の処理を付ければ、簡単ですが完成ですね(たぶん)。
●cart.php
<?php
require('./Cart.phl');
?>
<?php
function showItem($cart)
{
if (get_class($cart) != 'cart') {
die('Illegal object ' . get_class($cart));
}
$contents = '';
$items = $cart->getItems();
while (list($_cd, $_num) = each($items)) {
$contents .= '<tr>' .
'<td>' . $_cd . '</td>' .
'<td> '.
'<input type="text" value="' . $_num . '" size="3">'.
'</td>' .
'</tr>';
}
echo '<table border="1">' . $contents . '</table>';
}
?>
<?php
session_start();
echo 'SESSION_ID=' . strip_tags(session_id()) . '<p />';
$item_cd = '';
$num = 0;
$mode = '';
if (isset($_POST['item_cd']) && $_POST['item_cd'] != '') {
$item_cd = $_POST['item_cd'];
}
if (isset($_POST['num']) && ereg('[1-9][0-9]*', $_POST['num'])) {
$num = (int)$_POST['num'];
}
if (isset($_POST['mode'])) {
$mode = $_POST['mode'];
}
if ($mode == 'ADD' && ($item_cd == '' || $num == 0)) {
$mode = '';
}
if ($_SESSION['_cart'] == null){
$_SESSION['_cart'] = new Cart();
echo '新しい買い物かごです。<p />';
}
if ($mode == 'ADD') {
if ($item_cd != '' && $num != ''){
echo '商品を追加します<p />';
$_SESSION['_cart']->addItem($item_cd, $num);
}
} else if ($mode == 'DEL') {
echo '買い物かごの中身をクリアします<p />';
$_SESSION['_cart']->clear();
}
showItem($_SESSION['_cart']);
?>
<script language='JavaScript'>
<!--
function go_next(_md) {
var frm = document.cart;
frm.mode.value = _md;
frm.submit();
}
//-->
</script>
<form name='cart' action='cart.php' method='post'>
<input type='hidden' name='mode'>
商品コード:<input type='text' name='item_cd'><br />
個数:<input type='text' name='num'><br />
<input type='button' value='商品を追加' onClick='go_next("ADD")'>
<input type='button' value='すべてクリア' onClick='go_next("DEL")'>
</form>
●Cart.phl
<?php
class Cart
{
var $item;
function Cart()
{
$this->item = array();
}
function addItem($item_cd, $num)
{
if (!isset($this->item[$item_cd])) {
$this->item[$item_cd] = 0;
}
$this->item[$item_cd] += $num;
if ($this->item[$item_cd] < 0) {
$this->item[$item_cd] = 0;
}
}
function clear()
{
$this->item = array();
}
function getItems()
{
return $this->item;
}
}
?>
|