Getting the Duration of a Video with PHP

I wanted to calculate the duration of a video in seconds as in integer variable. For this I needed software outside of PHP. So, I decided to use the open source video encoding library, avconv, running on Linux Mint / Ubuntu.

If you pass a video to avconv, it returns meta-data about the video, including its duration, e.g.

$avconv -i myvideo.mp4
avconv version 0.8.10-6:0.8.10-0ubuntu0.13.10.1, Copyright (c) 2000-2013 the Libav developers
built on Feb  6 2014 20:53:28 with gcc 4.8.1
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'myvideo.mp4':
major_brand     : mp42
minor_version   : 1
compatible_brands: mp42mp41
creation_time   : 2013-11-23 13:44:21
Duration: 00:00:03.76, start: 0.000000, bitrate: 393 kb/s

A search on the Ubuntu forums returned an easy way to parse the above output using Linux scripting1.

avconv -i myvideo.mp4 2>&1 | grep 'Duration' | awk '{print $2}' | sed s/,//

This will extract the timestamp after the text after “Duration”. The 2>&1 is important as avconv sends it’s output to standard error rather than standard output. I coded this in PHP as below.

$cmd = "avconv -i '$video' 2>&1 | grep 'Duration' | awk '{print $2}' | sed s/,//";
exec($cmd, $result, $error);
$duration = $result[0];

Once, I had the above data (e.g.  “00:00:03.76”) in a string, I needed to convert it to an integer value. Further research returned the following snippet of PHP code

list($hours,$mins,$secs) = explode(':',$duration);
$seconds = mktime($hours,$mins,$secs) - mktime(0,0,0);

The first mktime returned a timestamp relative to the current time, so we need to subtract the number of seconds from the current timestamp at midnight. This gives us the number of seconds in our video as an integer value.


Raguet Roman, 2012, accessed  21 April 2014, <>.
2012, Stack Overflow, accessed  21 April 2014,<>.