Get duration of video in PHP

If you are developing an application in PHP or any of its frameworks (e.g. Laravel) where you are allowing users to upload videos, and you want to get the duration of the video then this article is for you.

Getting the duration of user uploaded video has many benefits. One of them is you can limit the video duration. For example, you might have seen in TikTok that it allows videos of 15 or seconds only (for free users). To upload videos of longer length, you need to get their premium membership.

First, you need to install a library called getID3. You can install it by running the following command in your terminal:

composer require james-heinrich/getid3

I have a file saved at the following path:

http://127.0.0.1:8000/storage/video.mp4

The following PHP code will get the duration of the above video:

$remote_filename = "storage/" . $file_path;

if ($fp_remote = fopen($remote_filename, "rb"))
{
    $local_temp_filename = tempnam("/tmp", "getID3");

    if ($fp_local = fopen($local_temp_filename, "wb"))
    {
        while ($buffer = fread($fp_remote, 8192))
        {
            fwrite($fp_local, $buffer);
        }
        fclose($fp_local);

        $get_id3 = new \getID3;
        $file_info = $get_id3->analyze($local_temp_filename);

        $seconds = $file_info["playtime_seconds"];
        $seconds = round($seconds);

        return $seconds;
    }
}

Explanation:

  1. Line #3 will open the uploaded file in read-only binary mode.
  2. Line #5 will create a temporary file name in the directory “/tmp” (you do not need to create this directory). And the prefix of that file name will be “getID3”.
  3. Line #7 will open the temporary file in write-only binary mode.
  4. Line #9 reads the whole remote file in chunks of 8 KB per chunk. The loop continues until there is no more data, meaning the video file is read completely.
  5. Line #11 will write the buffer from the remote file to the local temporary file.
  6. Line #15 creates a new instance for class getID3. This class handles the metadata information for multimedia files like videos etc.
  7. Line #16 extracts the metadata information from local temporary file.
  8. Line #18 will get the seconds from the $file_info array.
  9. Finally, line #19 will round the number to the nearest whole number.

If you want to know how to get the size of uploaded file in PHP, you can check our this tutorial. Let me know if that works for you.