如何在PHP中实现类似文件大小展示的视频码率与帧尺寸功能?
Hey there! 🎥
PHP doesn’t have built-in functions to read video metadata like bitrate or frame dimensions directly—which explains why you came up empty in the official function index. But no worries, there are two solid ways to pull this info, depending on what you can set up on your server:
1. Use the PHP FFmpeg Extension
If you have permission to install extensions on your server, the php-ffmpeg library makes this task a breeze. First, install the extension (follow the setup docs for your server environment), then you can use a function like this to fetch the metadata:
use FFMpeg\FFMpeg; function get_video_metadata($video_path) { $ffmpeg = FFMpeg::create(); $video = $ffmpeg->open($video_path); $metadata = $video->getMetadata(); $video_stream = $video->getStreams()->videos()->first(); // Convert bitrate to Kbps for readability $bitrate = $metadata->get('bit_rate') / 1000; // Grab frame dimensions $dimensions = $video_stream->getDimensions(); return [ 'bitrate' => round($bitrate, 2) . ' Kbps', 'resolution' => $dimensions->getWidth() . 'x' . $dimensions->getHeight() ]; }
You can pair this with your existing display_size function to show all key video details together.
2. Call FFmpeg/ffprobe via Command Line
If installing extensions isn’t an option, you can use the ffprobe tool (included with the FFmpeg suite) via PHP’s command execution functions. This requires FFmpeg to be installed on your server.
Here’s a safe, parsed function to get the metadata:
function get_video_metadata_cli($video_path) { // Escape the path to avoid command injection risks $safe_path = escapeshellarg($video_path); // Run ffprobe to fetch JSON-formatted metadata $command = "ffprobe -v quiet -print_format json -show_format -show_streams $safe_path"; $output = shell_exec($command); $metadata = json_decode($output, true); if (!$metadata) { return false; // Handle metadata read errors here } // Extract bitrate (convert to Kbps) $bitrate = isset($metadata['format']['bit_rate']) ? $metadata['format']['bit_rate'] / 1000 : 0; // Pull resolution from the first video stream $video_stream = array_values(array_filter($metadata['streams'], fn($s) => $s['codec_type'] === 'video'))[0]; return [ 'bitrate' => round($bitrate, 2) . ' Kbps', 'resolution' => $video_stream['width'] . 'x' . $video_stream['height'] ]; }
Quick Tips:
- For the command line method, always use
escapeshellarg()on user-provided file paths to prevent malicious command injection. - If you get a "command not found" error, double-check that FFmpeg/ffprobe is installed and accessible to your PHP process (you might need to use the full path to the executable).
You can wrap the output of these functions in display logic just like your display_size function—for example, adding styled units for bitrate or formatting the resolution text.
内容的提问来源于stack exchange,提问作者Gerag2

