一、LAMP架构概述
LAMP是Linux + Apache + MySQL + PHP的经典开源Web技术栈组合,是构建动态网站和电子商务平台的理想选择。
LAMP核心组件:
– Linux:稳定安全的操作系统基础
– Apache:功能强大的Web服务器
– MySQL:可靠的关系型数据库
– PHP:灵活的服务器端脚本语言
为什么选择LAMP做电商:
– ✅ 完全开源,无授权费用
– ✅ 社区活跃,资料丰富
– ✅ 性能稳定,承载能力强
– ✅ 扩展灵活,易于定制
二、电商网站架构设计
2.1 技术架构图
┌─────────────────────────────────────────┐
│ 用户浏览器 │
└──────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Apache HTTP Server │
│ (负载均衡 + SSL) │
└──────────────┬──────────────────────────┘
│
┌───────┴───────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ PHP-FPM │ │ 静态资源 │
│ (应用层) │ │ (CSS/JS) │
└──────┬──────┘ └─────────────┘
│
▼
┌─────────────────────────────────────────┐
│ MySQL数据库 │
│ (商品/订单/用户/支付) │
└─────────────────────────────────────────┘
2.2 目录结构规划
/var/www/ecommerce/
├── public/
│ ├── index.php
│ ├── assets/
│ │ ├── css/
│ │ ├── js/
│ │ └── images/
│ └── uploads/
├── app/
│ ├── controllers/
│ ├── models/
│ ├── views/
│ └── config/
├── core/
│ ├── Database.php
│ ├── Router.php
│ └── Session.php
└── vendor/
三、环境搭建步骤
3.1 安装Linux系统
推荐使用Ubuntu 22.04 LTS或CentOS 8:
# Ubuntu更新系统
apt update && apt upgrade -y
# 设置时区
timedatectl set-timezone Asia/Shanghai
# 创建应用用户
useradd -m -s /bin/bash www-data
3.2 安装Apache
# Ubuntu安装
apt install apache2 -y
# 启用必要模块
a2enmod rewrite ssl headers
# 启动服务
systemctl enable apache2
systemctl start apache2
3.3 安装MySQL
# 安装MySQL 8.0
apt install mysql-server -y
# 安全配置
mysql_secure_installation
# 创建电商数据库
mysql -u root -p
CREATE DATABASE ecommerce CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'ec_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';
GRANT ALL PRIVILEGES ON ecommerce.* TO 'ec_user'@'localhost';
FLUSH PRIVILEGES;
3.4 安装PHP
# 安装PHP 8.2及扩展
apt install php8.2 php8.2-fpm php8.2-mysql php8.2-gd \
php8.2-curl php8.2-mbstring php8.2-xml php8.2-zip \
php8.2-bcmath php8.2-intl -y
# 配置PHP-FPM
systemctl enable php8.2-fpm
systemctl start php8.2-fpm
四、电商数据库设计
4.1 核心数据表
-- 用户表
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
phone VARCHAR(20),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_email (email)
);
-- 商品分类表
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
parent_id INT DEFAULT 0,
slug VARCHAR(100) UNIQUE,
INDEX idx_parent (parent_id)
);
-- 商品表
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT NOT NULL,
name VARCHAR(200) NOT NULL,
slug VARCHAR(200) UNIQUE,
description TEXT,
price DECIMAL(10,2) NOT NULL,
stock INT DEFAULT 0,
image_url VARCHAR(500),
status ENUM('active','inactive') DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_category (category_id),
INDEX idx_status (status),
FOREIGN KEY (category_id) REFERENCES categories(id)
);
-- 购物车表
CREATE TABLE cart_items (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY unique_cart (user_id, product_id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
-- 订单表
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
order_no VARCHAR(50) UNIQUE NOT NULL,
user_id INT NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
status ENUM('pending','paid','shipped','completed','cancelled') DEFAULT 'pending',
shipping_address TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user (user_id),
INDEX idx_status (status),
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- 订单详情表
CREATE TABLE order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
product_name VARCHAR(200),
price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(id)
);
五、核心功能实现
5.1 数据库连接类
<?php
class Database {
private static $instance = null;
private $pdo;
private function __construct() {
$host = 'localhost';
$db = 'ecommerce';
$user = 'ec_user';
$pass = 'StrongPassword123!';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO($dsn, $user, $pass, $options);
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance->pdo;
}
}
?>
5.2 商品列表展示
<?php
class ProductController {
public function index($category = null) {
$pdo = Database::getInstance();
$sql = "SELECT * FROM products WHERE status = 'active'";
if ($category) {
$sql .= " AND category_id = (SELECT id FROM categories WHERE slug = ?)";
}
$sql .= " ORDER BY created_at DESC LIMIT 20";
$stmt = $pdo->prepare($sql);
$stmt->execute($category ? [$category] : []);
$products = $stmt->fetchAll();
include 'views/products/list.php';
}
public function show($slug) {
$pdo = Database::getInstance();
$stmt = $pdo->prepare(
"SELECT p.*, c.name as category_name
FROM products p
JOIN categories c ON p.category_id = c.id
WHERE p.slug = ?"
);
$stmt->execute([$slug]);
$product = $stmt->fetch();
if (!$product) {
http_response_code(404);
include 'views/404.php';
return;
}
include 'views/products/detail.php';
}
}
?>
5.3 购物车功能
<?php
class CartController {
public function add($productId, $quantity = 1) {
$pdo = Database::getInstance();
$userId = $_SESSION['user_id'];
// 检查商品库存
$stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
$stmt->execute([$productId]);
$product = $stmt->fetch();
if ($product['stock'] < $quantity) {
return ['error' => '库存不足'];
}
// 添加或更新购物车
$stmt = $pdo->prepare(
"INSERT INTO cart_items (user_id, product_id, quantity)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE quantity = quantity + ?"
);
$stmt->execute([$userId, $productId, $quantity, $quantity]);
return ['success' => true, 'message' => '已添加到购物车'];
}
public function getCart() {
$pdo = Database::getInstance();
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare(
"SELECT c.*, p.name, p.price, p.image_url, p.stock,
(c.quantity * p.price) as subtotal
FROM cart_items c
JOIN products p ON c.product_id = p.id
WHERE c.user_id = ?"
);
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
public function getCartTotal() {
$items = $this->getCart();
return array_sum(array_column($items, 'subtotal'));
}
}
?>
5.4 订单创建
<?php
class OrderController {
public function create($shippingAddress) {
$pdo = Database::getInstance();
$userId = $_SESSION['user_id'];
$cart = (new CartController())->getCart();
if (empty($cart)) {
return ['error' => '购物车为空'];
}
$total = array_sum(array_column($cart, 'subtotal'));
$orderNo = 'ORD' . date('YmdHis') . rand(1000, 9999);
try {
$pdo->beginTransaction();
// 创建订单
$stmt = $pdo->prepare(
"INSERT INTO orders (order_no, user_id, total_amount, shipping_address, status)
VALUES (?, ?, ?, ?, 'pending')"
);
$stmt->execute([$orderNo, $userId, $total, $shippingAddress]);
$orderId = $pdo->lastInsertId();
// 添加订单详情
$stmt = $pdo->prepare(
"INSERT INTO order_items (order_id, product_id, product_name, price, quantity)
VALUES (?, ?, ?, ?, ?)"
);
foreach ($cart as $item) {
$stmt->execute([
$orderId, $item['product_id'], $item['name'], $item['price'], $item['quantity']
]);
}
// 清空购物车
$pdo->prepare("DELETE FROM cart_items WHERE user_id = ?")->execute([$userId]);
$pdo->commit();
return ['success' => true, 'order_no' => $orderNo];
} catch (Exception $e) {
$pdo->rollBack();
return ['error' => '订单创建失败:' . $e->getMessage()];
}
}
}
?>
六、Apache虚拟主机配置
<VirtualHost *:80>
ServerName yourdomain.com
ServerAlias www.yourdomain.com
DocumentRoot /var/www/ecommerce/public
<Directory /var/www/ecommerce/public>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
# URL重写规则
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</Directory>
ErrorLog ${APACHE_LOG_DIR}/ecommerce_error.log
CustomLog ${APACHE_LOG_DIR}/ecommerce_access.log combined
</VirtualHost>
七、安全加固措施
7.1 防SQL注入
<?php
// ✅ 使用预处理语句
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
// ❌ 禁止直接拼接
$sql = "SELECT * FROM users WHERE email = '$email'"; // 危险!
?>
7.2 防XSS攻击
<?php
function h($string) {
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
// 在视图中使用
echo h($product['name']);
?>
7.3 CSRF防护
<?php
// 生成Token
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// 表单中添加
echo '<input type="hidden" name="csrf_token" value="' . h($_SESSION['csrf_token']) . '">';
// 验证Token
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF验证失败');
}
?>
八、性能优化
8.1 启用OPcache
; php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
8.2 数据库索引优化
-- 分析慢查询
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
-- 使用EXPLAIN优化查询
EXPLAIN SELECT * FROM products WHERE category_id = 5 AND status = 'active';
九、常见问题
Q1: LAMP适合大型电商吗?
A: 适合。大型电商平台可采用分布式架构:多台PHP应用服务器 + 主从MySQL + Redis缓存 + CDN。
Q2: 如何处理支付对接?
A: 对接支付宝/微信支付SDK,使用异步通知处理支付结果,务必验证签名。
Q3: 如何保证库存准确?
A: 使用数据库事务+行级锁,或使用Redis原子操作。
十、总结
使用LAMP架构搭建电商网站的关键步骤:
- 规划系统架构和目录结构
- 搭建LAMP运行环境
- 设计数据库表结构
- 实现核心功能(商品、购物车、订单)
- 配置Apache虚拟主机
- 加固安全防护
- 性能优化与监控
LAMP架构成熟稳定,是中小型电商网站的理想选择,配合CDN和缓存可支撑较高并发。
注:本文基于2026年LAMP技术编写,实际部署请参考官方最新文档。