php实现视频
PHP 实现视频功能
视频上传处理
使用 PHP 处理视频上传需要确保服务器配置允许大文件上传。修改 php.ini 中的以下参数:
upload_max_filesize = 100Mpost_max_size = 100Mmax_execution_time = 300
通过 HTML 表单上传视频文件:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="video">
<input type="submit" value="Upload">
</form>
在 upload.php 中处理上传:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["video"]["name"]);
if (move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)) {
echo "Video uploaded successfully.";
} else {
echo "Error uploading video.";
}
视频播放嵌入
使用 HTML5 的 <video> 标签嵌入上传的视频:
<video width="640" height="360" controls>
<source src="uploads/example.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
视频转码处理
使用 FFmpeg 进行视频转码(需服务器安装 FFmpeg):
$video_path = "uploads/example.mp4";
$output_path = "uploads/example_converted.mp4";
$command = "ffmpeg -i $video_path -c:v libx264 -crf 23 -preset fast -c:a aac -b:a 128k $output_path";
exec($command, $output, $return_code);
if ($return_code === 0) {
echo "Video converted successfully.";
} else {
echo "Error converting video.";
}
视频缩略图生成
使用 FFmpeg 从视频中提取缩略图:
$video_path = "uploads/example.mp4";
$thumbnail_path = "uploads/thumbnail.jpg";
$command = "ffmpeg -i $video_path -ss 00:00:05 -vframes 1 $thumbnail_path";
exec($command);
视频信息获取
使用 FFprobe(FFmpeg 的一部分)获取视频信息:
$video_path = "uploads/example.mp4";
$command = "ffprobe -v quiet -print_format json -show_format -show_streams $video_path";
$output = shell_exec($command);
$video_info = json_decode($output, true);
print_r($video_info);
视频流媒体
实现简单的视频流媒体:
$file = 'uploads/example.mp4';
if (file_exists($file)) {
header('Content-Type: video/mp4');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
注意事项
- 确保服务器有足够的存储空间和处理能力处理视频文件
- 考虑使用 CDN 分发大视频文件
- 对于生产环境,建议使用专业的视频处理服务或转码服务
- 注意视频版权和用户上传内容的安全审查







