PHP 网站存储代码优化指南

存储是网站性能的关键部分,合理的存储策略可以显著提升网站性能。以下是 PHP 网站中关于存储优化的代码示例和最佳实践。

1. 文件存储优化

1.1 文件上传处理

php

* 安全处理文件上传

function handleFileUpload(array $file, string $uploadDir = 'uploads'): ?array {

// 验证上传错误

if ($file['error'] !== UPLOAD_ERR_OK) {

throw new RuntimeException('. $file['error']);

// 验证文件类型

$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

if (!in_array($file['type'], $allowedTypes)) {

throw new RuntimeException('不允许的文件类型');

// 验证文件大小 (例如限制为5MB)

$maxSize = 5 * 1024 * 1024;

if ($file['size'] > $maxSize) {

throw new RuntimeException('文件大小超过限制');

// 创建上传目录(如果不存在)

if (!file_exists($uploadDir)) {

mkdir($uploadDir, 0755, true);

// 生成安全文件名

$extension = pathinfo($file['name'], PATHINFO_EXTENSION);

$filename = bin2hex(random_bytes(16)) . '.' . $extension;

$destination = $uploadDir . DIRECTORY_SEPARATOR . $filename;

// 移动上传文件

if (!move_uploaded_file($file['tmp_name'], $destination)) {

throw new RuntimeException('无法移动上传文件');

return [

'path' => $destination,

'filename' => $filename,

'size' => $file['size'],

'mime_type' => $file['type']

// 使用示例

try {

$uploadedFile = handleFileUpload($_FILES['userfile']);

echo "文件上传成功: " . $uploadedFile['filename'];

} catch (RuntimeException $e) {

echo "错误: " . $e->getMessage();

1.2 文件缓存实现

php

* 简单的文件缓存系统

class FileCache {

private string $cacheDir;

private int $defaultTtl;

public function __construct(string $cacheDir = 'cache', int $defaultTtl = 3600) {

$this->cacheDir = rtrim($cacheDir, '/');

$this->defaultTtl = $defaultTtl;

if (!file_exists($this->cacheDir)) {

mkdir($this->cacheDir, 0755, true);

public function set(string $key, $value, int $ttl = null): bool {

$filename = $this->getCacheFile($key);

$expires = time() + ($ttl ?? $this->defaultTtl);

$data = [

'expires' => $expires,

'data' => $value

return (bool)file_put_contents($filename, serialize($data));

public function get(string $key) {

$filename = $this->getCacheFile($key);

if (!file_exists($filename)) {

return null;

$data = unserialize(file_get_contents($filename));

if ($data['expires'] < time()) {

$this->delete($key);

return null;

return $data['data'];

public function delete(string $key): bool {

$filename = $this->getCacheFile($key);

return file_exists($filename) ? unlink($filename) : false;

public function clear(): bool {

return $this->deleteFiles($this->cacheDir);

private function getCacheFile(string $key): string {

return $this->cacheDir . DIRECTORY_SEPARATOR . md5($key) . '.cache';

private function deleteFiles(string $dir): bool {

$files = array_diff(scandir($dir), ['.', '..']);

foreach ($files as $file) {

$path = $dir . DIRECTORY_SEPARATOR . $file;

if (is_dir($path)) {

$this->deleteFiles($path);

} else {

unlink($path);

return rmdir($dir);

// 使用示例

$cache = new FileCache();

$cache->set('popular_products', ['prod1', 'prod2', 'prod3'], 1800);

$products = $cache->get('popular_products');