


Detailed explanation of shopping website implementation examples using PHP
The following editor will bring you a case of implementing a multi-functional shopping website in PHP. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
1. The page that needs to be implemented:
Index.aspx: Browse the product page and display the product list , users can click "Add to Cart".
ViewCart.aspx: View the shopping cart page, which displays purchased product information. You can click "Delete" and "Submit to add an order to purchase" the product
ViewAccount.aspx: View personal account balance
Login.aspx: Login page
2. Implementation functions:
1. Display product list
2. Implement the purchase function, and dynamically display the quantity of goods in the shopping cart and the total price of the goods when purchasing
3. After clicking to view the shopping cart, the purchased goods will be displayed. Pay attention to the "Purchase Quantity" column. If you click to buy a product multiple times, its "Purchase Quantity" will continue to increase.
4. Delete the purchased items in the shopping cart.
If the "purchase quantity" of a product is 1, when you click "Delete", the product will be deleted directly from the shopping cart;
If the "purchase quantity" of the product is greater than 1 , when you click "Delete" once, the purchase quantity will be reduced by 1. When the purchase quantity of the product reaches 1, and then click Delete, the product will be deleted
5. After viewing the shopping cart, you can also click "Browse Products" to continue purchasing. And the quantity of goods purchased and the total price are displayed above.
6. After "View Shopping Cart", you can submit the order.
But when submitting an order, the following functions must be completed:
(a) Check whether the user is logged in. If not logged in, go to the Login.aspx page
(b) Check whether the user account balance is sufficient for this purchase
(c) Check whether the inventory quantity is sufficient for this purchase
(d) If all the above conditions are met
i. Deduct the total price of this purchase from the user account
ii. Deduct the purchase quantity of each product from the product inventory
iii. Add it to the order table and order content table Add the product information of this purchase
7. Click View Account to view the user’s account balance
The operation code is as follows:
1. First make a login page: loginpage.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <style> .title{ margin-left: 750px; margin-top: 150px; } .quanju{ margin-left: 650px; margin-top: -460px; } .name,.pwd{ max-width: 120px; } .yangshi1{ margin-top: 200px; } .header{ width: 100%; height: 80px; background: #e0e0e0; } .ps{ margin-left: 100px; margin-top: -100px; } </style> <body> <form class="form-horizontal" role="form" action="dengluchuli.php" method="post"> <p class="header"> <img src="/static/imghwm/default1.png" data-src="img/logo.png" class="lazy" style="max-width:90%" style="max-width:90%" / alt="Detailed explanation of shopping website implementation examples using PHP" > <p >果 蔬 网</p> </p> <h3 id="用户登录">用户登录</h3> <img class="ps lazy" src="/static/imghwm/default1.png" data-src="./img/果蔬专场.jpg" style="max-width:90%" style="max-width:90%" / alt="Detailed explanation of shopping website implementation examples using PHP" > <p class="quanju"> <p class="form-group yangshi1"> <label for="firstname" class="col-sm-2 control-label">用户名:</label> <p class="col-sm-10"> <input type="text" class="form-control name" name="uid" placeholder="请输入用户名"> </p> </p> <p class="form-group yangshi2"> <label for="lastname" class="col-sm-2 control-label">密码:</label> <p class="col-sm-10"> <input type="text" class="form-control pwd" name="pwd" placeholder="请输入密码"> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <p class="checkbox"> <label> <input type="checkbox"> 保存密码 </label> <label> <input type="checkbox"> 下次自动登录 </label> </p> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-warning" value="登录" onclick="return login()" > 登录 </button> </p> </p> </p> </form> </body> <script> function login(){ var uid = document.getElementsByTagName("input")[0].value; if(uid==""){ alert("请输入用户名!"); return false; } var pwd = document.getElementsByTagName("input")[1].value; if(pwd==""){ alert("请输入密码!"); return false; } } </script> </html>
The effect is as shown:
2. Create a login processing page: dengluchuli.php
<?php session_start(); $uid = $_POST["uid"]; $pwd = $_POST["pwd"]; require_once "./DBDA.class.php"; $db = new DBDA(); $sql = "select * from login where username='{$uid}'"; $arr = $db->query($sql,0); if($arr[0][2]==$pwd && !empty($pwd)){ $_SESSION["uid"]=$uid; header("location:shopping_list.php"); }else{ echo "登陆失败!"; }
This way you can contact the database. This is the login account of the database. and password, verify the account and password, and then jump to the homepage: shopping_list.php
3. Now make the homepage page: shopping_list.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <body> <h2 id="水果列表">水果列表</h2> <?php session_start(); //1.找出购物车中多少种商品和总价 $uid = $_SESSION["uid"]; if(empty($_SESSION["uid"])){ header("location:loginpage.php"); exit; } require_once "./DBDA.class.php"; $db = new DBDA(); //如果购物车有商品,取出值 if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; $numbers = count($arr); foreach($arr as $k=>$v){ //$v[0];//水果名称 //$v[1];//购买数量 $sql = "select * from fruit where ids='{$v[0]}'"; $attr = $db->query($sql,0); $dj = $attr[0][2]; //单价 $sum = $sum+$dj*$v[1]; //总价=单价*数量 } } echo @"<p style='margin-left: 250px'>购物车中商品总数为{$numbers}个,商品总价为:{$sum}元</p>"; ?> <a href="loginpage.php" rel="external nofollow" > 登录 </a> <table class="table table-bordered" > <thead> <tr> <th>代号</th> <th>名称</th> <th>价格</th> <th>产地</th> <th>库存</th> <th>操作</th> </tr> </thead> <tbody> <?php $sql = "select * from fruit"; $arr = $db->query($sql,0); foreach($arr as $v){ echo "<tr> <td>{$v[0]}</td> <td>{$v[1]}</td> <td>{$v[2]}</td> <td>{$v[3]}</td> <td>{$v[4]}</td> <td><a href='shoppingchuli.php?ids={$v[0]}'>加入购物车</a></td> </tr>"; } ?> </tbody> </table> <a href="add_list.php" rel="external nofollow" >查看购物车</a> </body> </html>
4. Then make the homepage processing page: shoppingchuli.php
##
<?php session_start(); //取到传过来的主键值,并且添加到购物车的SESSION里面 $ids = $_GET["ids"]; //如果是第一次添加购物车,造一个二维数组存到SESSION里面 //如果不是第一次添加,有两种情况 //1.如果该商品购物车里面不存在,造一个一维数组扔到二维里面 //2.如果该商品在购物车存在,让数量加1 if(empty($_SESSION["gwd"])){ //如果是第一次添加购物车,造一个二维数组存到SESSION里面 $arr = array( array($ids,1)); $_SESSION["gwd"]=$arr; }else{ $arr=$_SESSION["gwd"]; if(deep_in_array($ids,$arr)){ //如果该商品在购物车存在,让数量加1 foreach($arr as $k=>$v){ if($v[0]==$ids){ $arr[$k][1]++; } } $_SESSION["gwd"]=$arr; }else{ //如果该商品购物车里面不存在,造一个一维数组扔到二维里面 $arr=$_SESSION["gwd"]; $attr=array($ids,1); $arr[]=$attr; $_SESSION["gwd"]=$arr; } } header("location:shopping_list.php"); function deep_in_array($value, $array) { foreach($array as $item) { if(!is_array($item)) { if ($item == $value) { return true; } else { continue; } } if(in_array($value, $item)) { return true; } else if(deep_in_array($value, $item)) { return true; } } return false; }The effect is as shown:
5. Then view the shopping cart page, you can see the products in the shopping cart, the unit price and the total price: gouwuche.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <?php session_start(); $uid = $_SESSION["uid"]; if(empty($_SESSION["uid"])){ header("location:loginpage.php"); exit; } ?> <body> <h2 id="购物车清单">购物车清单</h2> <table class="table table-bordered" > <thead> <tr> <th>代号</th> <th>名称</th> <th>价格</th> <th>产地</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <?php require_once "./DBDA.class.php"; $db = new DBDA(); if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; $numbers = count($arr); foreach($arr as $k=>$v){ //$v[0];$v[1]; $sql = "select * from fruit where ids='{$v[0]}'"; $a = $db->query($sql,0); //var_dump($v[1]); echo "<tr> <td>{$v[0]}</td> <td>{$a[0][1]}</td> <td>{$a[0][2]}</td> <td>{$a[0][3]}</td> <td>{$v[1]}</td> <td><a href='goodsdel.php?zj={$k}'>删除</a></td> </tr>"; $dj = $a[0][2]; $sum = $sum+$dj*$v[1]; } } //echo "<p style='margin-left: 250px;'>购物车中商品总数为{$numbers}个,商品总价为:{$sum}元</p>"; ?> </tbody> </table> <a href="submit_order.php?ids={$v[0]}" rel="external nofollow" >提交订单</a> </body> </html>The effect is as shown in the figure:
6. Do the deletion processing page goodsdel .php
<?php session_start(); $zj = $_GET["zj"]; //如果该水果数量大于1,减1 //如果该水果数量等于1 移除 $arr = $_SESSION["gwd"]; if($arr[$zj][1]>1){ $arr[$zj][1]=$arr[$zj][1]-1; }else{ unset($arr[$zj]); //清除数组 $arr=array_values($arr); //重新索引数组 } $_SESSION["gwd"] = $arr; header("location:add_list.php");
7.. Then make the submission page: tijiao.php
<?php session_start(); $ids = $_GET["ids"]; //查看余额 $uid = $_SESSION["uid"]; require_once "./DBDA.class.php"; $db = new DBDA(); $sql = "select account from login where username='{$uid}'"; $arr = $db->query($sql,0); $aye = $arr[0][0];//余额 //var_dump($aye); if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; //$numbers = count($arr); foreach($arr as $v){ $sql = "select * from fruit where ids='{$v[0]}'"; $price = $db->query($sql,0); $dj = $price[0][2]; $sum = $sum+$dj*$v[1]; } }else{ echo "您还未购买商品!"; //header("shopping_list.php"); exit; } //判断余额是否满足购买 if($aye>=$sum){ //判断库存 foreach($arr as $v){ $skc = "select name,numbers from fruit where ids='{$v[0]}'"; $akc = $db->query($sql,0); var_dump($akc); $kc = $akc[0][4];//库存 //var_dump($kc); if($kc<$v[1]){ echo "库存不足!"; exit; } } //提交订单 //账户扣除余额 $skye = "update login set account=account-{$sum} where username='{$uid}'"; $zhye = $db->query($skye); //扣除库存 foreach($arr as $v){ $skckc = "update fruit set numbers=numbers-{$v[1]} where ids='{$v[0]}'"; $sykc = $db->query($skckc); } //添加订单 $ddh = date("Y-m-d H:i:s"); $time = time(); $stjd = "insert into orders values('{$time}','{$uid}','{$ddh}')"; $wcdh = $db->query($stjd); //添加订单详情 foreach($arr as $v){ $ddxq = "insert into orderdetails values('','{$ddh}','{$v[0]}','{$v[1]}')"; $axq = $db->query($ddxq); } }else{ echo "余额不足,请充值!"; exit; } header("location:shopping_list.php");The user account balance has been reduced:
The above is the detailed content of Detailed explanation of shopping website implementation examples using PHP. For more information, please follow other related articles on the PHP Chinese website!

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor
