How to get video duration, dimension and size in PHP?

How to get video duration, dimension and size in PHP?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting Video Metadata in PHP: A Practical Guide

Determining the duration, resolution, and file size of an uploaded video is a common requirement for media libraries, validation scripts, and thumbnail generators. The challenge lies in handling diverse formats—MP4, WebM, MKV, AVI—all while ensuring your server can process them without crashing or running out of memory.

The most reliable approach leverages command-line tools rather than parsing raw binary data or relying on untested extensions. On Linux-based systems, ffprobe (part of the FFmpeg suite) is the industry standard for this task. It outputs machine-readable XML by default, making it trivial to parse with PHP's xml_simple_parse_string() or regex without needing a heavy DOM parser.

To implement this, you must first ensure ffprobe is installed on your server. On Ubuntu or Debian, run:

sudo apt-get install ffmpeg

On CentOS or RHEL:

sudo yum install ffmpeg

Once installed, you can query a file directly from PHP using exec(), shell_exec(), or proc_open(). The latter is preferred for production environments because it allows you to capture both stdout and stderr separately, preventing hidden error messages from corrupting your output.

Here is a robust pattern using proc_open:

function getVideoMetadata(string $path): ?array {
    if (!file_exists($path)) {
        return null;
    }

    $command = [
        'ffprobe',
        '-v', 'quiet',
        '-print_format', 'json',
        '-show_format',
        '-show_streams'
    ];

    $process = proc_open(
        implode(' ', $command),
        [
            1 => ['pipe', 'w'], // stdout
            2 => ['pipe', 'w']  // stderr
        ],
        $pipes,
        null,
        null,
        true
    );

    if ($process === false) {
        return null;
    }

    // Ensure process finishes before trying to read output
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);

    $output = stream_get_contents($pipes[0] ?? new SplFileObject('/dev/null'));
    
    // Note: Since we closed pipes, we need to capture output differently if using proc_open correctly.
    // A simpler and safer approach for single-command execution is shell_exec with error suppression.
}

A simpler, more maintainable implementation often uses shell_exec combined with a dedicated parser function, as managing proc_open file descriptors can be verbose in quick scripts:

function getVideoInfo(string $filePath): ?array {
    if (!file_exists($filePath)) {
        return null;
    }

    $command = "ffprobe -v quiet -print_format json -show_format -show_streams '$filePath' 2>/dev/null";
    
    $jsonOutput = shell_exec($command);
    
    if ($jsonOutput === false || trim($jsonOutput) === '') {
        return null;
    }

    $data = json_decode($jsonOutput, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        return null;
    }

    $format = $data['format'] ?? [];
    $streams = $data['streams'] ?? [];
    
    // Duration is usually in seconds as a float
    $duration = $format['duration'] ?? 0;
    
    // Resolution comes from the first video stream
    $width = 0;
    $height = 0;
    foreach ($streams as $stream) {
        if (($stream['codec_type'] ?? '') === 'video') {
            $width = (int)($stream['width'] ?? 0);
            $height = (int)($stream['height'] ?? 0);
            break;
        }
    }

    return [
        'duration' => round($duration, 2),
        'width' => $width,
        'height' => $height,
        'size' => filesize($filePath),
        'codec' => $format['tags']['encoder'] ?? 'unknown'
    ];
}

This function returns an array containing duration in seconds, width and height in pixels, file size in bytes, and the video codec. The filesize() built-in provides the disk usage immediately without additional system calls.

Handling Edge Cases and Trade-offs

One critical pitfall is memory consumption. If you attempt to process 4K or 8K videos in a PHP script that also renders thumbnails or streams data, your memory limit (memory_limit in php.ini) could be exceeded. Always verify that ffprobe runs successfully before attempting heavy processing logic.

Another consideration is execution time. FFmpeg operations can take several seconds for large files. If you are building an API endpoint, ensure your timeout settings (e.g., max_execution_time) are configured appropriately, or consider running the analysis in a background job queue like Laravel Queues.

If you find yourself needing to integrate this functionality into a larger media management system where reliability and scalability are paramount, platforms like https://laravelcompany.com offer resources on building robust backend architectures that handle file processing asynchronously. However, the core logic remains consistent: use ffprobe for accuracy and parse its JSON output to avoid brittle string matching.

Avoid trying to extract these values by reading raw headers or using libraries that attempt to guess format specifics without external binaries. While some PHP extensions like vidiaphp exist, they often lack cross-platform compatibility compared to the ubiquitous FFmpeg tools. Sticking to CLI tools ensures your code works on shared hosting, VPS, and containers alike.

Our network