引言

PHP图片上传大小

1. 修改php.ini文件

  • upload_max_filesize: 允许上传的文件最大尺寸。
  • post_max_size: 通过表单POST给PHP的所能接收的最大值。
  • memory_limit: 每个PHP页面所消耗的最大内存。

这些参数的单位默认为字节(B),可以通过在参数值后加上KM等表示千字节、兆字节等。

2. 设置示例

以下是一个修改php.ini文件的示例:

upload_max_filesize = 8M
post_max_size = 8M
memory_limit = 8M

3. 重启服务器

修改php.ini文件后,需要重启Apache服务器才能使更改生效。

图片上传优化技巧

1. 前端验证

function validateFileSize(file) {
  const maxFileSize = 8 * 1024 * 1024; // 8MB
  return file.size <= maxFileSize;
}

2. 后端验证

if ($_FILES['image']['size'] > 8 * 1024 * 1024) {
  die('文件大小超过');
}

3. 使用GD库进行图片处理

function resizeImage($imagePath, $maxWidth, $maxHeight) {
  list($width, $height) = getimagesize($imagePath);
  $ratio = min($maxWidth / $width, $maxHeight / $height);
  $newWidth = $width * $ratio;
  $newHeight = $height * $ratio;
  $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
  $sourceImage = imagecreatefromjpeg($imagePath);
  imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  imagejpeg($resizedImage, $imagePath);
}

4. 使用队列处理

// 使用队列处理图片上传
function uploadImage($filePath) {
  // 将图片上传任务添加到队列
  Queue::add('imageUpload', ['filePath' => $filePath]);
  
  // 后台处理队列中的图片上传任务
  Queue::process('imageUpload', function ($job) {
    // 上传图片逻辑
    $job->delete();
  });
}

总结