이 기사의 예에서는 PHP에서 구현된 장바구니 클래스를 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 구체적인 분석은 다음과 같습니다.
본 장바구니 클래스는 CodeIgniter의 장바구니 클래스 모방을 기반으로 구현되었습니다.
장바구니의 기본 기능은 다음과 같습니다.
1) 장바구니에 상품 추가
2) 장바구니에서 상품 삭제
3) 장바구니 품목 정보 업데이트 [1/-1]
4) 장바구니 항목 통계
1. 전체 프로젝트
2. 총 수량
3. 총액
5) 쇼핑 품목 수량 및 금액 계산
6) 장바구니 비우기
1. cart.php 파일:
<?php /** * * @author quanshuidingdang */ class Cart { //物品id及名称规则,调试信息控制 private $product_id_rule = '\.a-z0-9-_'; //小写字母 | 数字 | ._- private $product_name_rule = '\.\:a-z0-9-_';//小写字母 | 数字 | ._-: private $debug = TRUE; //购物车 private $_cart_contents = array(); /** * 构造函数 * * @param array */ public function __construct() { //是否第一次使用? if(isset($_SESSION['cart_contents'])) { $this->_cart_contents = $_SESSION['cart_contents']; } else { $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; } if($this->debug === TRUE) { //$this->_log("cart_create_success"); } } /** * 将物品加入购物车 * * @access public * @param array 一维或多维数组,必须包含键值名: id -> 物品ID标识, qty -> 数量(quantity), price -> 单价(price), name -> 物品姓名 * @return bool */ public function insert($items = array()) { //输入物品参数异常 if( ! is_array($items) OR count($items) == 0) { if($this->debug === TRUE) { $this->_log("cart_no_items_insert"); } return FALSE; } //物品参数处理 $save_cart = FALSE; if(isset($items['id'])) { if($this->_insert($items) === TRUE) { $save_cart = TRUE; } } else { foreach($items as $val) { if(is_array($val) AND isset($val['id'])) { if($this->_insert($val) == TRUE) { $save_cart = TRUE; } } } } //当插入成功后保存数据到session if($save_cart) { $this->_save_cart(); return TRUE; } return FALSE; } /** * 更新购物车物品信息 * * @access public * @param array * @return bool */ public function update($items = array()) { //输入物品参数异常 if( !is_array($items) OR count($items) == 0) { if($this->debug === TRUE) { $this->_log("cart_no_items_insert"); } return FALSE; } //物品参数处理 $save_cart = FALSE; if(isset($items['rowid']) AND isset($items['qty'])) { if($this->_update($items) === TRUE) { $save_cart = TRUE; } } else { foreach($items as $val) { if(is_array($val) AND isset($val['rowid']) AND isset($val['qty'])) { if($this->_update($val) === TRUE) { $save_cart = TRUE; } } } } //当更新成功后保存数据到session if($save_cart) { $this->_save_cart(); return TRUE; } return FALSE; } /** * 获取购物车物品总金额 * * @return int */ public function total() { return $this->_cart_contents['cart_total']; } /** * 获取购物车物品种类 * * @return int */ public function total_items() { return $this->_cart_contents['total_items']; } /** * 获取购物车 * * @return array */ public function contents() { return $this->_cart_contents; } /** * 获取购物车物品options * * @param string * @return array */ public function options($rowid = '') { if($this->has_options($rowid)) { return $this->_cart_contents[$rowid]['options']; } else { return array(); } } /** * 清空购物车 * */ public function destroy() { unset($this->_cart_contents); $this->_cart_contents['cart_total'] = 0; $this->_cart_contents['total_items'] = 0; unset($_SESSION['cart_contents']); } /** * 判断购物车物品是否有options选项 * * @param string * @return bool */ private function has_options($rowid = '') { if( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0) { return FALSE; } return TRUE; } /** * 插入数据 * * @access private * @param array * @return bool */ private function _insert($items = array()) { //输入物品参数异常 if( ! is_array($items) OR count($items) == 0) { if($this->debug === TRUE) { $this->_log("cart_no_data_insert"); } return FALSE; } //如果物品参数无效(无id/qty/price/name) if( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name'])) { if($this->debug === TRUE) { $this->_log("cart_items_data_invalid"); } return FALSE; } //去除物品数量左零及非数字字符 $items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty'])); $items['qty'] = trim(preg_replace('/^([0]+)/i', '', $items['qty'])); //如果物品数量为0,或非数字,则我们对购物车不做任何处理! if( ! is_numeric($items['qty']) OR $items['qty'] == 0) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_invalid"); } return FALSE; } //物品ID正则判断 if( ! preg_match('/^['.$this->product_id_rule.']+$/i', $items['id'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(id)_invalid"); } return FALSE; } //物品名称正则判断 if( ! preg_match('/^['.$this->product_name_rule.']+$/i', $items['name'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(name)_invalid"); } return FALSE; } //去除物品单价左零及非数字(带小数点)字符 $items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price'])); $items['price'] = trim(preg_replace('/^([0]+)/i', '', $items['price'])); //如果物品单价非数字 if( ! is_numeric($items['price'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(price)_invalid"); } return FALSE; } //生成物品的唯一id if(isset($items['options']) AND count($items['options']) >0) { $rowid = md5($items['id'].implode('', $items['options'])); } else { $rowid = md5($items['id']); } //加入物品到购物车 unset($this->_cart_contents[$rowid]); $this->_cart_contents[$rowid]['rowid'] = $rowid; foreach($items as $key => $val) { $this->_cart_contents[$rowid][$key] = $val; } return TRUE; } /** * 更新购物车物品信息(私有) * * @access private * @param array * @return bool */ private function _update($items = array()) { //输入物品参数异常 if( ! isset($items['rowid']) OR ! isset($items['qty']) OR ! isset($this->_cart_contents[$items['rowid']])) { if($this->debug == TRUE) { $this->_log("cart_items_data_invalid"); } return FALSE; } //去除物品数量左零及非数字字符 $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']); $items['qty'] = preg_replace('/^([0]+)/i', '', $items['qty']); //如果物品数量非数字,对购物车不做任何处理! if( ! is_numeric($items['qty'])) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_invalid"); } return FALSE; } //如果购物车物品数量与需要更新的物品数量一致,则不需要更新 if($this->_cart_contents[$items['rowid']]['qty'] == $items['qty']) { if($this->debug === TRUE) { $this->_log("cart_items_data(qty)_equal"); } return FALSE; } //如果需要更新的物品数量等于0,表示不需要这件物品,从购物车种清除 //否则修改购物车物品数量等于输入的物品数量 if($items['qty'] == 0) { unset($this->_cart_contents[$items['rowid']]); } else { $this->_cart_contents[$items['rowid']]['qty'] = $items['qty']; } return TRUE; } /** * 保存购物车数据到session * * @access private * @return bool */ private function _save_cart() { //首先清除购物车总物品种类及总金额 unset($this->_cart_contents['total_items']); unset($this->_cart_contents['cart_total']); //然后遍历数组统计物品种类及总金额 $total = 0; foreach($this->_cart_contents as $key => $val) { if( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty'])) { continue; } $total += ($val['price'] * $val['qty']); //每种物品的总金额 $this->_cart_contents[$key]['subtotal'] = ($val['price'] * $val['qty']); } //设置购物车总物品种类及总金额 $this->_cart_contents['total_items'] = count($this->_cart_contents); $this->_cart_contents['cart_total'] = $total; //如果购物车的元素个数少于等于2,说明购物车为空 if(count($this->_cart_contents) <= 2) { unset($_SESSION['cart_contents']); return FALSE; } //保存购物车数据到session $_SESSION['cart_contents'] = $this->_cart_contents; return TRUE; } /** * 日志记录 * * @access private * @param string * @return bool */ private function _log($msg) { return @file_put_contents('cart_err.log', $msg, FILE_APPEND); } } /*End of file cart.php*/ /*Location /htdocs/cart.php*/
2. cart_demo.php 파일은 다음과 같습니다.
<?php session_start(); require_once('cart.php'); $items = array( 0 => array( 'id' => 'sp001', 'qty' => 20, 'price' => '10.50', 'name' => 'a002', 'options' => array( 'made' => 'china', 'company' => 'bgi' ) ), 1 => array( 'id' => 'sp002', 'qty' => 1, 'price' => '3.50', 'name' => 'b002' ) ); $arr = array( 'rowid' => '86dbb7cb58a667558b4bbb1f60330028', 'qty' => 21 ); $cart = new Cart(); $cart->insert($items); //var_dump($cart->contents()); $cart->update($arr); var_dump($cart->contents()); //$cart->destroy(); //var_dump($_SESSION['cart_contents']); /*end of php*/
이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.

세션 ID는 로그인시, 민감한 작업 전에 및 30 분마다 정기적으로 재생되어야합니다. 1. 세션 고정 공격을 방지하기 위해 로그인 할 때 세션 ID를 재생합니다. 2. 안전성을 향상시키기 위해 민감한 작업 전에 재생성. 3. 정기적 인 재생은 장기 활용 위험을 줄이지 만 사용자 경험을 평가해야합니다.

Session_SET_COOKIE_PARAMS () 함수를 통해 PHP에서 세션 쿠키 매개 변수 설정을 달성 할 수 있습니다. 1)이 기능을 사용하여 만료 시간, 경로, 도메인 이름, 보안 플래그 등과 같은 매개 변수를 설정하십시오. 2) call session_start ()를 호출하려면 매개 변수를 발효시킵니다. 3) 사용자 로그인 상태와 같은 요구에 따라 매개 변수를 동적으로 조정합니다. 4) 보안을 향상시키기 위해 안전하고 httponly 플래그 설정에주의를 기울이십시오.

PHP에서 세션을 사용하는 주요 목적은 다른 페이지간에 사용자의 상태를 유지하는 것입니다. 1) 세션은 Session_Start () 함수를 통해 시작되어 고유 한 세션 ID를 생성하고 사용자 쿠키에 저장합니다. 2) 세션 데이터는 서버에 저장되므로 로그인 상태 및 쇼핑 카트 컨텐츠와 같은 다른 요청간에 데이터를 전달할 수 있습니다.

하위 도메인 간의 세션을 공유하는 방법? 공통 도메인 이름에 대한 세션 쿠키를 설정하여 구현. 1. 세션 쿠키 도메인을 서버 측에서 .example.com으로 설정하십시오. 2. 메모리, 데이터베이스 또는 분산 캐시와 같은 적절한 세션 저장 방법을 선택하십시오. 3. 쿠키를 통해 세션 ID를 전달하면 서버는 ID를 기반으로 세션 데이터를 검색하고 업데이트합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)
