php实现上传视频文件
文件上传表单设计
创建HTML表单,设置enctype="multipart/form-data"以支持文件上传。表单需包含file类型的输入字段。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="video_file" accept="video/*">
<input type="submit" value="Upload">
</form>
服务器端验证处理
在PHP脚本中通过$_FILES超全局数组获取上传文件信息。需验证文件类型、大小及错误状态。
$targetDir = "uploads/";
$maxFileSize = 500 * 1024 * 1024; // 500MB
$allowedTypes = ['video/mp4', 'video/quicktime'];
if ($_FILES['video_file']['error'] !== UPLOAD_ERR_OK) {
die("Upload error: " . $_FILES['video_file']['error']);
}
if ($_FILES['video_file']['size'] > $maxFileSize) {
die("File exceeds maximum size limit");
}
if (!in_array($_FILES['video_file']['type'], $allowedTypes)) {
die("Invalid file type");
}
安全存储处理
生成唯一文件名防止冲突,使用move_uploaded_file()函数安全存储文件。

$fileExtension = pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION);
$newFileName = uniqid() . '.' . $fileExtension;
$targetPath = $targetDir . $newFileName;
if (!move_uploaded_file($_FILES['video_file']['tmp_name'], $targetPath)) {
die("Failed to move uploaded file");
}
文件类型深度验证
除MIME类型外,建议使用finfo扩展进行二进制内容验证。
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$detectedType = finfo_file($finfo, $_FILES['video_file']['tmp_name']);
finfo_close($finfo);
if (!in_array($detectedType, $allowedTypes)) {
unlink($_FILES['video_file']['tmp_name']);
die("File content does not match declared type");
}
大文件上传优化
对于大视频文件,可在php.ini中调整以下参数:

upload_max_filesize = 512M
post_max_size = 520M
max_execution_time = 300
或通过.htaccess文件设置:
php_value upload_max_filesize 512M
php_value post_max_size 520M
php_value max_execution_time 300
分块上传实现
对于超大文件,可采用分块上传技术。前端使用JavaScript将文件分片,后端合并分片。
// 接收分片文件
$chunkNumber = $_POST['chunk'];
$totalChunks = $_POST['total'];
$tempDir = "temp_uploads/";
if (!file_exists($tempDir)) {
mkdir($tempDir, 0755, true);
}
$tempFilePath = $tempDir . $_FILES['file']['name'] . '.part' . $chunkNumber;
move_uploaded_file($_FILES['file']['tmp_name'], $tempFilePath);
// 合并分片
if ($chunkNumber == $totalChunks - 1) {
$finalPath = $targetDir . $_FILES['file']['name'];
$fp = fopen($finalPath, 'wb');
for ($i = 0; $i < $totalChunks; $i++) {
$chunkPath = $tempDir . $_FILES['file']['name'] . '.part' . $i;
$chunkContent = file_get_contents($chunkPath);
fwrite($fp, $chunkContent);
unlink($chunkPath);
}
fclose($fp);
}






