Table of Contents
php uses cookies to implement shopping cart, cookies shopping cart
Home Backend Development PHP Tutorial How to use cookies to implement a shopping cart in PHP, cookies shopping cart_PHP tutorial

How to use cookies to implement a shopping cart in PHP, cookies shopping cart_PHP tutorial

Jul 13, 2016 am 10:12 AM
cookie cookies php

php uses cookies to implement shopping cart, cookies shopping cart

The example in this article describes how PHP uses cookies to implement a shopping cart. Share it with everyone for your reference. The specific analysis is as follows:

The php shopping cart is used on e-commerce websites. It is like a supermarket shopping cart. After selecting the products, you first put them in your shopping cart and then wait for them to settle at the counter. This php shopping cart The car is fully implemented according to this principle. Interested friends can take a look. This example is implemented using cookies. The code is as follows:

Copy code The code is as follows:
/**
*Shopping cart cookies are saved with a storage period of 1 day. Note: The browser must support cookies to use
​*/
class cartapi {
private $cartarray = array(); // Two-dimensional array to store shopping cart
private $cartcount; // Count the number of shopping carts
public $expires = 86400; // Cookie expiration time, if it is 0, it will not be saved locally. The unit is seconds
/**
* Constructor initialization operation If $id is not empty, add it directly to the shopping cart
*
​*/
public function __construct($id = "",$name = "",$price1 = "",$price2 = "",$price3 = "",$count = "",$image = "",$expires = 86400 ) {
if ($id != "" && is_numeric($id)) {
$this->expires = $expires;
$this->addcart($id,$name,$price1,$price2,$price3,$count,$image);
}
}
/**
* Add items to cart
*
* @param int $id item number
* @param string $name product name
* @param decimal $price1 Product price
* @param decimal $price2 Product price
* @param decimal $price3 Product price
* @param int $count item quantity
* @param string $image product image
* @return If the product exists, add 1 to the original quantity and return false
​*/
public function addcart($id,$name,$price1,$price2,$price3,$count,$image) {
$this->cartarray = $this->cartview(); // Read and write data into the array
if ($this->checkitem($id)) { // Check whether the item exists
$this->modifycart($id,$count,0); // Add $count to the quantity of goods
Return false;
}
$this->cartarray[0][$id] = $id;
$this->cartarray[1][$id] = $name;
$this->cartarray[2][$id] = $price1;
$this->cartarray[3][$id] = $price2;
$this->cartarray[4][$id] = $price3;
$this->cartarray[5][$id] = $count;
$this->cartarray[6][$id] = $image;
$this->save();
}
/**
* Modify items in shopping cart
*
* @param int $id product number
* @param int $count item quantity
* @param int $flag Modification type 0: Add 1: Subtract 2: Modify 3: Clear
* @return If the modification fails, return false
​*/
public function modifycart($id, $count, $flag = "") {
$tmpid = $id;
$this->cartarray = $this->cartview(); // Read and write data into the array
$tmparray = &$this->cartarray; // Reference
if (!is_array($tmparray[0])) return false;
if ($id < 1) {
Return false;
}
foreach ($tmparray[0] as $item) {
if ($item === $tmpid) {
switch ($flag) {
Case 0: // Add quantity. Generally $count is 1
$tmparray[5][$id] += $count;
        break;
Case 1: // Reduce quantity
$tmparray[5][$id] -= $count;
        break;
Case 2: // Modify quantity
If ($count == 0) {
​​​ unset($tmparray[0][$id]);
​​​ unset($tmparray[1][$id]);
​​​ unset($tmparray[2][$id]);
​​​ unset($tmparray[3][$id]);
​​​ unset($tmparray[4][$id]);
​​​ unset($tmparray[5][$id]);
​​​ unset($tmparray[6][$id]);
        break;
} else {
         $tmparray[5][$id] = $count;
        break;
        }
Case 3: // Clear items
        unset($tmparray[0][$id]);
        unset($tmparray[1][$id]);
        unset($tmparray[2][$id]);
        unset($tmparray[3][$id]);
        unset($tmparray[4][$id]);
        unset($tmparray[5][$id]);
        unset($tmparray[6][$id]);
        break;
Default:
        break;
}
}
}
$this->save();
}
/**
* Clear shopping cart
*
​*/
public function removeall() {
$this->cartarray = array();
$this->save();
}
/**
* View shopping cart information
*
* @return array Returns a two-dimensional array
​*/
public function cartview() {
$cookie = strips tutorial lashes($_cookie['cartapi']);
if (!$cookie) return false;
$tmpunserialize = unserialize($cookie);
Return $tmpunserialize;
}
/**
* Check if there are items in the shopping cart
*
* @return bool If there is a product, return true, otherwise false
​*/
public function checkcart() {
$tmparray = $this->cartview();
if (count($tmparray[0]) < 1) {
Return false;
}
Return true;
}
/**
* Product Statistics
*
* @return array Returns a one-dimensional array $arr[0]: the total price of product 1 $arr[1: the total price of product 2 $arr[2]: the total price of product 3 $arr[3]: the total price of product 3 Quantity
​*/
public function countprice() {
$tmparray = $this->cartarray = $this->cartview();
$outarray = array(); //One-dimensional array
// 0 is the total price of product 1
// 1 is the total price of product 2
// 2 is the total price of product 3
// 3 is the total quantity of products
$i = 0;
if (is_array($tmparray[0])) {
foreach ($tmparray[0] as $key=>$val) {
$outarray[0] += $tmparray[2][$key] * $tmparray[5][$key];
$outarray[1] += $tmparray[3][$key] * $tmparray[5][$key];
$outarray[2] += $tmparray[4][$key] * $tmparray[5][$key];
$outarray[3] += $tmparray[5][$key];
$i++;
}
}
return $outarray;
}
/**
* Count the number of products
*
* @return int
​*/
public function cartcount() {
$tmparray = $this->cartview();
$tmpcount = count($tmparray[0]);
$this->cartcount = $tmpcount;
return $tmpcount;
}
/**
* Save the product If you do not use the construction method, this method must use
*
​*/
public function save() {
$tmparray = $this->cartarray;
$tmpserialize = serialize($tmparray);
setcookie("cartapi",$tmpserialize,time()+$this->expires);
}
/**
* Check if the items in the shopping cart exist
*
* @param int $id
* @return bool if true otherwise false
​*/
private function checkitem($id) {
$tmparray = $this->cartarray;
if (!is_array($tmparray[0])) return;
foreach ($tmparray[0] as $item) {
if ($item === $id) return true;
}
return false;
}
}
?>

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/925132.htmlTechArticlephp uses cookies to implement a shopping cart, cookies shopping cart This article describes how php uses cookies to implement a shopping cart . Share it with everyone for your reference. The specific analysis is as follows: p...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles