PHP Session Class (Shopping cart Class) _php tutorial

Source: Internet
Author: User
Tags php session sprintf
The session is a more commonly used in PHP, we often use it as a record of global page information, if the user login, background management, there is a common in the shopping cart class, I would like to introduce you.

About the application of the session in PHP is not less, one of the most important functions, session in the network application, called "session", we generally understand to store a specific user session required information, so that when the user jumps between site pages, stored session value is not lost, Instead, it survives throughout the user's session. In layman's words, when user A is online, an ID (a) value is created to save it, and if your ID (a) value is not logged off, the next time you surf the web, the site will remember your ID (a) value, and you can call your ID (a) on the Internet, such as Welcome ID (a) Value is accessed once again.

About the application of the session value in PHP is very simple, as long as the top input session_start () to start the session, the following can be used session, this is only a small site application method, in fact, the session itself has many properties, such as Session period, call Session,session data validity period, session save, session logoff and so on, if you have these attributes, it seems to be a relatively standardized session application sessions.

The following is a complete session class, the integration of the session's most basic property values, which, open, close and clean is in line with the PHP programming code, which is also a good habit. Small explanation, if the site is not a large number of use of the session class, basically there is no need to use the session class.

The code is as follows Copy Code


/**
* File Description Session Class
* =================================================================
* File name session.class.php
* -----------------------------------------------------------------
* Applicable environment: Php5.2.x/mysql 5.0.x
* -----------------------------------------------------------------
* Author 04ie. Com
* -----------------------------------------------------------------
* Creation Time 2010-2-1
* =================================================================
*/
Class Session
{
/**
* Session Default Validity time
* @access Public
* @var Ineger $_expiry
*/
public $_expiry = 3600;
/**
* Valid domain name
* @access Public
* @var String $_domain
*/
Public $_domain = '. phpfamily.cn ';
Initialization
Public Function __construct ()
{
Ini_set (' session.use_trans_id ', 0);
Ini_set (' Session.gc_maxlifetime ', $this->_expiry);
Ini_set (' Session.use_cookie ', 1);
Ini_set (' Session.cookie_path ', '/');
Ini_set (' Session.cookie_domain ', $this->_domain);
Session_module_name (' user ');
Session_set_save_handler (
Array (& $this, ' Open '),
Array (& $this, ' Close '),
Array (& $this, ' read '),
Array (& $this, ' write '),
Array (& $this, ' Destroy '),
Array (& $this, ' GC ')
);
Session_Start ();
}
/**
* Open Session
* @access Public
* @param string $savePath
* @param string $sName
* @return True
*/
Public function open ($savePath, $sName)
{
$this->_conn = mysql_connect (' localhost ', ' root ', ');
mysql_select_db (' databases ');
mysql_query (' SET NAMES ' utf8 "');
return true;
}
/**
* Close Session
* @access Public
* @return BOOL
*/
Public Function Close ()
{
Return Mysql_close ($this->_conn);
}
/**
* Read session
* @access Public
* @param string $sid SessionID
* @return Mixed
*/
Public function read ($SID)
{
$sql = "Select data from Sessions WHERE sessionid= '%s '";
$sql = sprintf ($sql, $sid);
$res = mysql_query ($sql, $this->_conn);
$row = Mysql_fetch_assoc ($res);
Return! $row? Null: $row [' data '];
}
/**
* Write session
* @access Public
* @param string $sid SessionID
* @param string $data Serialize the contents of the session after serialization
* @return
*/
Public function Write ($sid, $data)
{
$expiry = time () + $this->_expiry;
$sql = "REPLACE into sessions (Sessionid,expiratio
N,data) VALUES ('%s ', '%d ', '%s ');
$sql = sprintf ($sql, $sid, $expiry, $data);
mysql_query ($sql, $this->_conn);
return true;
}
/**
* Destroy session
* @access Public
* @param string $sid SessionID
* @return
*/
Public function Destroy ($SID)
{
$sql = "DELETE from sessions WHERE sessionid= '%s '";
$sql = sprintf ($sql, $sid);
mysql_query ($sql, $this->_conn);
return true;
}
/**
* Cleanup expired session
* @access Public
* @param integer $time
* @return
*/
Public Function gc ($time = 0)
{
$sql = "DELETE from sessions WHERE expiration < '%d '";
$sql = sprintf ($sql, Time ());
mysql_query ($sql, $this->_conn);
mysql_query (' OPTIMIZE TABLE sessions ');
return true;
}

Now let's look at a PHP session shopping Cart Class

The code is as follows Copy Code

Class cart{
Public Function Cart () {
if (!isset ($_session[' cart ')) {
$_session[' cart ' = Array ();
}
}

/*
Add Item
param int $id Commodity primary key
String $name Product Name
Float $price Product Price
int $num Number of purchases
*/
Public Function AddItem ($id, $name, $price, $num, $img) {
If the item already exists, add the quantity directly
if (isset ($_session[' cart '] [$id])) {
$this->incnum ($id, $num);
Return
}
$item = Array ();
$item [' id '] = $id;
$item [' name '] = $name;
$item [' price '] = $price;
$item [' num '] = $num;
$item [' img '] = $img;
$_session[' cart ' [$id] = $item;
}

/*
Modify the number of items in your shopping cart
int $id Commodity PRIMARY key
int $num The quantity of a product after it has been modified, that is, a product directly
The number of changes to $num
*/
Public Function Modnum ($id, $num =1) {
if (!isset ($_session[' cart '] [$id])) {
return false;
}
$_session[' cart ' [$id] [' num '] = $num;
}

/*
Number of items +1
*/
Public Function Incnum ($id, $num =1) {
if (isset ($_session[' cart '] [$id])) {
$_session[' cart ' [$id] [' num '] + = $num;
}
}

/*
Number of items-1
*/
Public Function Decnum ($id, $num =1) {
if (isset ($_session[' cart '] [$id])) {
$_session[' cart ' [$id] [' num ']-= $num;
}

If the number is reduced to 0, delete the item
if ($_session[' cart ' [$id] [' num '] <1) {
$this->delitem ($id);
}
}

/*
Delete Item
*/
Public Function Delitem ($id) {
unset ($_session[' cart '] [$id]);
}

/*
Get a single item
*/
Public Function GetItem ($id) {
return $_session[' cart ' [$id];
}

/*
Inquire about the types of items in your shopping cart
*/
Public Function getcnt () {
return count ($_session[' cart ');
}

/*
Check the number of items in your shopping cart
*/
Public Function Getnum () {
if ($this->getcnt () = = 0) {
The number of species is 0, and the number is 0.
return 0;
}

$sum = 0;
$data = $_session[' cart '];
foreach ($data as $item) {
$sum + = $item [' num '];
}
return $sum;
}

/*
Total amount of items in the shopping cart
*/
Public Function GetPrice () {
The quantity is 0, the price is 0
if ($this->getcnt () = = 0) {
return 0;
}
$price = 0.00;
foreach ($this->items as $item) {
$price + = $item [' num '] * $item [' price '];
}
Return sprintf ("%01.2f", $price);
}

/*
Empty shopping Cart
*/
Public Function Clear () {
$_session[' cart ' = Array ();
}
}

http://www.bkjia.com/PHPjc/633150.html www.bkjia.com true http://www.bkjia.com/PHPjc/633150.html techarticle The session is a more commonly used in PHP, we often use it as a record of global page information, if the user login, background management, there is a common in the shopping cart class, the next ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.