How to retrive geolocation information from JPEG EXIF data? - php

I was working on image manipulation with php gd library. Just now God appeared and told me that we can retrieve exif data from jpeg, tiff images.But, he did not tell me how!
I tried surfing about it and found some posts about retrieving the data. All was good here on earth until I tried getting geo-location data. I couldn't find any solution to get that data.

I mentioned in the comments exif_read_data. Now that I'm at my desk I can elaborate a bit more. I created a function a while back to do exactly this:
// get geo-data from image
function get_image_location($file) {
if (is_file($file)) {
$info = exif_read_data($file);
if ($info !== false) {
$direction = array('N', 'S', 'E', 'W');
if (isset($info['GPSLatitude'], $info['GPSLongitude'], $info['GPSLatitudeRef'], $info['GPSLongitudeRef']) &&
in_array($info['GPSLatitudeRef'], $direction) && in_array($info['GPSLongitudeRef'], $direction)) {
$lat_degrees_a = explode('/',$info['GPSLatitude'][0]);
$lat_minutes_a = explode('/',$info['GPSLatitude'][1]);
$lat_seconds_a = explode('/',$info['GPSLatitude'][2]);
$lng_degrees_a = explode('/',$info['GPSLongitude'][0]);
$lng_minutes_a = explode('/',$info['GPSLongitude'][1]);
$lng_seconds_a = explode('/',$info['GPSLongitude'][2]);
$lat_degrees = $lat_degrees_a[0] / $lat_degrees_a[1];
$lat_minutes = $lat_minutes_a[0] / $lat_minutes_a[1];
$lat_seconds = $lat_seconds_a[0] / $lat_seconds_a[1];
$lng_degrees = $lng_degrees_a[0] / $lng_degrees_a[1];
$lng_minutes = $lng_minutes_a[0] / $lng_minutes_a[1];
$lng_seconds = $lng_seconds_a[0] / $lng_seconds_a[1];
$lat = (float) $lat_degrees + ((($lat_minutes * 60) + ($lat_seconds)) / 3600);
$lng = (float) $lng_degrees + ((($lng_minutes * 60) + ($lng_seconds)) / 3600);
$lat = number_format($lat, 7);
$lng = number_format($lng, 7);
//If the latitude is South, make it negative.
//If the longitude is west, make it negative
$lat = $info['GPSLatitudeRef'] == 'S' ? $lat * -1 : $lat;
$lng = $info['GPSLongitudeRef'] == 'W' ? $lng * -1 : $lng;
return array(
'lat' => $lat,
'lng' => $lng
);
}
}
}
return false;
}
This function is intended to work with file uploads, for example:
if (($geo = get_image_location($_FILES['file']['tmp_name'])) && !empty($geo)) {
// upload file
} else {
// file does not appear to contain any location information
}
That should give you a good start.

Related

Detecting and storing length of audio files in a table [duplicate]

Is there any PHP function that will give me the MP3 duration. I looked at ID 3 function but i don't see any thing there for duration and apart from this,id3 is some kind of tag,which will not be there in all MP3 so using this will not make any sense.
This should work for you, notice the getduration function: http://www.zedwood.com/article/127/php-calculate-duration-of-mp3
Install getid3, but if you only need duration, you can delete all but these modules:
module.audio.mp3.php
module.tag.id3v1.php
module.tag.apetag.php
module.tag.id3v2.php
Access the duration with code like this:
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($pathName);
$len= #$ThisFileInfo['playtime_string']; // playtime in minutes:seconds, formatted string
Get it at Sourceforge
I have passed so many time, but without getID3 (http://getid3.sourceforge.net/) to get duration of audio file not possible.
1) First download library of getID3 using below link:
https://github.com/JamesHeinrich/getID3/archive/master.zip
2) Try this below code:
<?php
include("getid3/getid3.php");
$filename = 'bcd4ecc6bf521da9b9a2d8b9616d1505.wav';
$getID3 = new getID3;
$file = $getID3->analyze($filename);
$playtime_seconds = $file['playtime_seconds'];
echo gmdate("H:i:s", $playtime_seconds);
?>
You can get the duration of an mp3 or many other audio/video files by using ffmpeg.
Install ffmpeg in your server.
Make sure that php shell_exec is not restricted in your php.
// Discriminate only the audio/video files you want
if(preg_match('/[^?#]+\.(?:wma|mp3|wav|mp4)/', strtolower($file))){
$filepath = /* your file path */;
// execute ffmpeg form linux shell and grab duration from output
$result = shell_exec("ffmpeg -i ".$filepath.' 2>&1 | grep -o \'Duration: [0-9:.]*\'');
$duration = str_replace('Duration: ', '', $result); // 00:05:03.25
//get the duration in seconds
$timeArr = preg_split('/:/', str_replace('s', '', $duration[0]));
$t = $this->_times[$file] = (($timeArr[3])? $timeArr[3]*1 + $timeArr[2] * 60 + $timeArr[1] * 60 * 60 : $timeArr[2] + $timeArr[1] * 60)*1000;
}
<?php
class MP3File
{
protected $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
public static function formatTime($duration) //as hh:mm:ss
{
//return sprintf("%d:%02d", $duration/60, $duration%60);
$hours = floor($duration / 3600);
$minutes = floor( ($duration - ($hours * 3600)) / 60);
$seconds = $duration - ($hours * 3600) - ($minutes * 60);
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}
//Read first mp3 frame only... use for CBR constant bit rate MP3s
public function getDurationEstimate()
{
return $this->getDuration($use_cbr_estimate=true);
}
//Read entire file, frame by frame... ie: Variable Bit Rate (VBR)
public function getDuration($use_cbr_estimate=false)
{
$fd = fopen($this->filename, "rb");
$duration=0;
$block = fread($fd, 100);
$offset = $this->skipID3v2Tag($block);
fseek($fd, $offset, SEEK_SET);
while (!feof($fd))
{
$block = fread($fd, 10);
if (strlen($block)<10) { break; }
//looking for 1111 1111 111 (frame synchronization bits)
else if ($block[0]=="\xff" && (ord($block[1])&0xe0) )
{
$info = self::parseFrameHeader(substr($block, 0, 4));
if (empty($info['Framesize'])) { return $duration; } //some corrupt mp3 files
fseek($fd, $info['Framesize']-10, SEEK_CUR);
$duration += ( $info['Samples'] / $info['Sampling Rate'] );
}
else if (substr($block, 0, 3)=='TAG')
{
fseek($fd, 128-10, SEEK_CUR);//skip over id3v1 tag size
}
else
{
fseek($fd, -9, SEEK_CUR);
}
if ($use_cbr_estimate && !empty($info))
{
return $this->estimateDuration($info['Bitrate'],$offset);
}
}
return round($duration);
}
private function estimateDuration($bitrate,$offset)
{
$kbps = ($bitrate*1000)/8;
$datasize = filesize($this->filename) - $offset;
return round($datasize / $kbps);
}
private function skipID3v2Tag(&$block)
{
if (substr($block, 0,3)=="ID3")
{
$id3v2_major_version = ord($block[3]);
$id3v2_minor_version = ord($block[4]);
$id3v2_flags = ord($block[5]);
$flag_unsynchronisation = $id3v2_flags & 0x80 ? 1 : 0;
$flag_extended_header = $id3v2_flags & 0x40 ? 1 : 0;
$flag_experimental_ind = $id3v2_flags & 0x20 ? 1 : 0;
$flag_footer_present = $id3v2_flags & 0x10 ? 1 : 0;
$z0 = ord($block[6]);
$z1 = ord($block[7]);
$z2 = ord($block[8]);
$z3 = ord($block[9]);
if ( (($z0&0x80)==0) && (($z1&0x80)==0) && (($z2&0x80)==0) && (($z3&0x80)==0) )
{
$header_size = 10;
$tag_size = (($z0&0x7f) * 2097152) + (($z1&0x7f) * 16384) + (($z2&0x7f) * 128) + ($z3&0x7f);
$footer_size = $flag_footer_present ? 10 : 0;
return $header_size + $tag_size + $footer_size;//bytes to skip
}
}
return 0;
}
public static function parseFrameHeader($fourbytes)
{
static $versions = array(
0x0=>'2.5',0x1=>'x',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $layers = array(
0x0=>'x',0x1=>'3',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $bitrates = array(
'V1L1'=>array(0,32,64,96,128,160,192,224,256,288,320,352,384,416,448),
'V1L2'=>array(0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384),
'V1L3'=>array(0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320),
'V2L1'=>array(0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256),
'V2L2'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
'V2L3'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
);
static $sample_rates = array(
'1' => array(44100,48000,32000),
'2' => array(22050,24000,16000),
'2.5' => array(11025,12000, 8000),
);
static $samples = array(
1 => array( 1 => 384, 2 =>1152, 3 =>1152, ), //MPEGv1, Layers 1,2,3
2 => array( 1 => 384, 2 =>1152, 3 => 576, ), //MPEGv2/2.5, Layers 1,2,3
);
//$b0=ord($fourbytes[0]);//will always be 0xff
$b1=ord($fourbytes[1]);
$b2=ord($fourbytes[2]);
$b3=ord($fourbytes[3]);
$version_bits = ($b1 & 0x18) >> 3;
$version = $versions[$version_bits];
$simple_version = ($version=='2.5' ? 2 : $version);
$layer_bits = ($b1 & 0x06) >> 1;
$layer = $layers[$layer_bits];
$protection_bit = ($b1 & 0x01);
$bitrate_key = sprintf('V%dL%d', $simple_version , $layer);
$bitrate_idx = ($b2 & 0xf0) >> 4;
$bitrate = isset($bitrates[$bitrate_key][$bitrate_idx]) ? $bitrates[$bitrate_key][$bitrate_idx] : 0;
$sample_rate_idx = ($b2 & 0x0c) >> 2;//0xc => b1100
$sample_rate = isset($sample_rates[$version][$sample_rate_idx]) ? $sample_rates[$version][$sample_rate_idx] : 0;
$padding_bit = ($b2 & 0x02) >> 1;
$private_bit = ($b2 & 0x01);
$channel_mode_bits = ($b3 & 0xc0) >> 6;
$mode_extension_bits = ($b3 & 0x30) >> 4;
$copyright_bit = ($b3 & 0x08) >> 3;
$original_bit = ($b3 & 0x04) >> 2;
$emphasis = ($b3 & 0x03);
$info = array();
$info['Version'] = $version;//MPEGVersion
$info['Layer'] = $layer;
//$info['Protection Bit'] = $protection_bit; //0=> protected by 2 byte CRC, 1=>not protected
$info['Bitrate'] = $bitrate;
$info['Sampling Rate'] = $sample_rate;
$info['Framesize'] = self::framesize($layer, $bitrate, $sample_rate, $padding_bit);
$info['Samples'] = $samples[$simple_version][$layer];
return $info;
}
private static function framesize($layer, $bitrate,$sample_rate,$padding_bit)
{
if ($layer==1)
return intval(((12 * $bitrate*1000 /$sample_rate) + $padding_bit) * 4);
else //layer 2, 3
return intval(((144 * $bitrate*1000)/$sample_rate) + $padding_bit);
}
}
?>
<?php
$mp3file = new MP3File("Chal_Halke.mp3");//http://www.npr.org/rss/podcast.php?id=510282
$duration1 = $mp3file->getDurationEstimate();//(faster) for CBR only
$duration2 = $mp3file->getDuration();//(slower) for VBR (or CBR)
echo "duration: $duration1 seconds"."\n";
?>
There is no native php function to do this.
Depending on your server environment, you may use a tool such as MP3Info.
$length = shell_exec('mp3info -p "%S" sample.mp3'); // total time in seconds
As earlier, I provided a solution for both mp3 and WAV files, Now this solution is specifically for the only WAV file with more precision but with longer evaluation time than the earlier solution.
function calculateWavDuration( $file ) {
$fp = fopen($file, 'r');
if (fread($fp, 4) == "RIFF") {
fseek($fp, 20);
$raw_header = fread($fp, 16);
$header = unpack('vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits', $raw_header);
$pos = ftell($fp);
while (fread($fp, 4) != "data" && !feof($fp)) {
$pos++;
fseek($fp, $pos);
}
$raw_header = fread($fp, 4);
$data = unpack('Vdatasize', $raw_header);
$sec = $data[datasize] / $header[bytespersec];
$minutes = intval(($sec / 60) % 60);
$seconds = intval($sec % 60);
return str_pad($minutes, 2, "0", STR_PAD_LEFT) . ":" . str_pad($seconds, 2, "0", STR_PAD_LEFT);
}
}
$file = '1.wav'; //Enter File wav
calculateWavDuration($file);
The MP3 length is not stored anywhere (in the "plain" MP3 format), since MP3 is designed to be "split" into frames and those frames will remain playable.
http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
If you have no ID tag on which to rely, what you would need to do (there are tools and PHP classes that do this) is to read the whole MP3 file and sum the durations of each frame.
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($pathName);
// playtime in minutes:seconds, formatted string
$len = #$ThisFileInfo['playtime_string'];
//don't get playtime_string, but get playtime_seconds
$len = #$ThisFileInfo['playtime_seconds']*1000; //*1000 as calculate millisecond
I hope this helps you.
Finally, I developed a solution with my own calculations. This solution works best for mp3 and WAV files formats. However minor precision variations are expected. The solution is in PHP. I take little bit clue from WAV
function calculateFileSize($file){
$ratio = 16000; //bytespersec
if (!$file) {
exit("Verify file name and it's path");
}
$file_size = filesize($file);
if (!$file_size)
exit("Verify file, something wrong with your file");
$duration = ($file_size / $ratio);
$minutes = floor($duration / 60);
$seconds = $duration - ($minutes * 60);
$seconds = round($seconds);
echo "$minutes:$seconds minutes";
}
$file = 'apple-classic.mp3'; //Enter File Name mp3/wav
calculateFileSize($file);
If you have FFMpeg installed, getting the duration is quite simple with FFProbe
$filepath = 'example.mp3';
$ffprobe = \FFMpeg\FFProbe::create();
$duration = $ffprobe->format($filepath)->get('duration');
echo gmdate('H:i:s', $duration);
FFMpeg is mentioned elsewhere, but here's a fuller explanation and example implementation.
Install ffmpeg for your system. E.g., on Ubuntu:
apt-get update && apt-get -y install ffmpeg
Install php-ffmpeg using Composer:
composer require php-ffmpeg/php-ffmpeg
Example utility class
<?php
namespace App\Utils;
use FFMpeg\FFProbe;
class Audio
{
public static function duration(string $path): float
{
$probe = FFProbe::create();
return $probe->format($path)->get('duration');
}
}
Where $path is the absolute path or URL to your audio file. To use:
$duration = \App\Utils\Audio::duration($path);
echo $duration; // 24.476750
Of course, you can just use it directly where you need it. The point of the utility class example is to show how you use it. You'll want to try/catch calling it in a production setting. If you aren't using composer, see #awavi's answer.

Converting GPRMC GPS data to decimal format in PHP

Tracking devices have the data sent in the $GPRMC which is not what I use in my Code would be googling for a PHP converting method to decimal format no avail.
Just got the solution to this had to boil my head on the content of $GPRMC
sample format e.g $GPRMC,001225,A,2832.1834,N,08101.0536,W,12,25,251211,1.2,E,A*03
Where:
RMC Recommended Minimum sentence C
123519 Fix taken at 12:35:19 UTC
A Status A=active or V=Void.
4807.038,N Latitude 48 deg 07.038' N
01131.000,E Longitude 11 deg 31.000' E
022.4 Speed over the ground in knots
084.4 Track angle in degrees True
230394 Date - 23rd of March 1994
003.1,W Magnetic Variation
*6A The checksum data, always begins with *
And the code:
$gps = $_REQUEST['gps'];
if($gps){
$buffer = $gps;
if(substr($buffer, 0, 5)=='GPRMC'){
$gprmc = explode(',',$buffer);
$data1['lattitude_decimal'] = DMStoDEC($gprmc[3],'lattitude');
$data2['longitude_decimal'] = DMStoDEC($gprmc[5],'longitude');
$data = 'http://maps.google.com/maps?q='.$data1['lattitude_decimal'].','.$data2['longitude_decimal'].'+(PHP Decoded)&iwloc=A';
print_r($data);
echo "\n\n";
}
}
function DMStoDEC($dms, $longlat){
if($longlat == 'lattitude'){
$deg = substr($dms, 0, 2);
$min = substr($dms, 2, 8);
$sec = '';
}
if($longlat == 'longitude'){
$deg = substr($dms, 0, 3);
$min = substr($dms, 3, 8);
$sec='';
}
return $deg+((($min*60)+($sec))/3600);
}
?>
Hope this will help someone
That's the typical post request:
POST /RoyS/?acct=1234&dev=null&gprmc=$GPRMC,132201,A,3128.7540,N,14257.6714,W,000.0,000.0,290314,,*e HTTP/1.1" 200 33 "-" "-"
The line should be $gps = $_REQUEST['gprmc'];. Are you sure about this line?
if(substr($buffer, 0, 5)=='GPRMC') {
Shouldn't it be:
if(substr($buffer, 1, 5)=='GPRMC') {
?
and you definitely ignored NWSE letters!
formula acá
list($dato1, $dato2, $dato3, $lat, $dato5, $lon, $dato7, $velocidad, $dato9, $dato10, $dato11, $dato12) = explode(',', $input_gps);
$resultado_lat = $lat / 100;
list ($latitud_entero, $latitud_decimal) = explode('.', $resultado_lat);
$resultado_lat_minutos = $lat - ($latitud_entero * 100);
$resultado_lat_segundos = ($resultado_lat_minutos / 60);
$resultado_lat_final = $latitud_entero + $resultado_lat_segundos;
if ($dato5 == 'S'){
$resultado_lat_final = $resultado_lat_final * -1;
}
$resultado_lon = $lon / 100;
list ($longitud_entero, $longitud_decimal) = explode('.', $resultado_lon);
$resultado_lon_minutos = $lon - ($longitud_entero * 100);
$resultado_lon_segundos = ($resultado_lon_minutos / 60);
$resultado_lon_final = $longitud_entero + $resultado_lon_segundos;
if ($dato7 == 'W'){
$resultado_lon_final = $resultado_lon_final * -1;
}

PHP Function to get MP3 duration

Is there any PHP function that will give me the MP3 duration. I looked at ID 3 function but i don't see any thing there for duration and apart from this,id3 is some kind of tag,which will not be there in all MP3 so using this will not make any sense.
This should work for you, notice the getduration function: http://www.zedwood.com/article/127/php-calculate-duration-of-mp3
Install getid3, but if you only need duration, you can delete all but these modules:
module.audio.mp3.php
module.tag.id3v1.php
module.tag.apetag.php
module.tag.id3v2.php
Access the duration with code like this:
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($pathName);
$len= #$ThisFileInfo['playtime_string']; // playtime in minutes:seconds, formatted string
Get it at Sourceforge
I have passed so many time, but without getID3 (http://getid3.sourceforge.net/) to get duration of audio file not possible.
1) First download library of getID3 using below link:
https://github.com/JamesHeinrich/getID3/archive/master.zip
2) Try this below code:
<?php
include("getid3/getid3.php");
$filename = 'bcd4ecc6bf521da9b9a2d8b9616d1505.wav';
$getID3 = new getID3;
$file = $getID3->analyze($filename);
$playtime_seconds = $file['playtime_seconds'];
echo gmdate("H:i:s", $playtime_seconds);
?>
You can get the duration of an mp3 or many other audio/video files by using ffmpeg.
Install ffmpeg in your server.
Make sure that php shell_exec is not restricted in your php.
// Discriminate only the audio/video files you want
if(preg_match('/[^?#]+\.(?:wma|mp3|wav|mp4)/', strtolower($file))){
$filepath = /* your file path */;
// execute ffmpeg form linux shell and grab duration from output
$result = shell_exec("ffmpeg -i ".$filepath.' 2>&1 | grep -o \'Duration: [0-9:.]*\'');
$duration = str_replace('Duration: ', '', $result); // 00:05:03.25
//get the duration in seconds
$timeArr = preg_split('/:/', str_replace('s', '', $duration[0]));
$t = $this->_times[$file] = (($timeArr[3])? $timeArr[3]*1 + $timeArr[2] * 60 + $timeArr[1] * 60 * 60 : $timeArr[2] + $timeArr[1] * 60)*1000;
}
<?php
class MP3File
{
protected $filename;
public function __construct($filename)
{
$this->filename = $filename;
}
public static function formatTime($duration) //as hh:mm:ss
{
//return sprintf("%d:%02d", $duration/60, $duration%60);
$hours = floor($duration / 3600);
$minutes = floor( ($duration - ($hours * 3600)) / 60);
$seconds = $duration - ($hours * 3600) - ($minutes * 60);
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}
//Read first mp3 frame only... use for CBR constant bit rate MP3s
public function getDurationEstimate()
{
return $this->getDuration($use_cbr_estimate=true);
}
//Read entire file, frame by frame... ie: Variable Bit Rate (VBR)
public function getDuration($use_cbr_estimate=false)
{
$fd = fopen($this->filename, "rb");
$duration=0;
$block = fread($fd, 100);
$offset = $this->skipID3v2Tag($block);
fseek($fd, $offset, SEEK_SET);
while (!feof($fd))
{
$block = fread($fd, 10);
if (strlen($block)<10) { break; }
//looking for 1111 1111 111 (frame synchronization bits)
else if ($block[0]=="\xff" && (ord($block[1])&0xe0) )
{
$info = self::parseFrameHeader(substr($block, 0, 4));
if (empty($info['Framesize'])) { return $duration; } //some corrupt mp3 files
fseek($fd, $info['Framesize']-10, SEEK_CUR);
$duration += ( $info['Samples'] / $info['Sampling Rate'] );
}
else if (substr($block, 0, 3)=='TAG')
{
fseek($fd, 128-10, SEEK_CUR);//skip over id3v1 tag size
}
else
{
fseek($fd, -9, SEEK_CUR);
}
if ($use_cbr_estimate && !empty($info))
{
return $this->estimateDuration($info['Bitrate'],$offset);
}
}
return round($duration);
}
private function estimateDuration($bitrate,$offset)
{
$kbps = ($bitrate*1000)/8;
$datasize = filesize($this->filename) - $offset;
return round($datasize / $kbps);
}
private function skipID3v2Tag(&$block)
{
if (substr($block, 0,3)=="ID3")
{
$id3v2_major_version = ord($block[3]);
$id3v2_minor_version = ord($block[4]);
$id3v2_flags = ord($block[5]);
$flag_unsynchronisation = $id3v2_flags & 0x80 ? 1 : 0;
$flag_extended_header = $id3v2_flags & 0x40 ? 1 : 0;
$flag_experimental_ind = $id3v2_flags & 0x20 ? 1 : 0;
$flag_footer_present = $id3v2_flags & 0x10 ? 1 : 0;
$z0 = ord($block[6]);
$z1 = ord($block[7]);
$z2 = ord($block[8]);
$z3 = ord($block[9]);
if ( (($z0&0x80)==0) && (($z1&0x80)==0) && (($z2&0x80)==0) && (($z3&0x80)==0) )
{
$header_size = 10;
$tag_size = (($z0&0x7f) * 2097152) + (($z1&0x7f) * 16384) + (($z2&0x7f) * 128) + ($z3&0x7f);
$footer_size = $flag_footer_present ? 10 : 0;
return $header_size + $tag_size + $footer_size;//bytes to skip
}
}
return 0;
}
public static function parseFrameHeader($fourbytes)
{
static $versions = array(
0x0=>'2.5',0x1=>'x',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $layers = array(
0x0=>'x',0x1=>'3',0x2=>'2',0x3=>'1', // x=>'reserved'
);
static $bitrates = array(
'V1L1'=>array(0,32,64,96,128,160,192,224,256,288,320,352,384,416,448),
'V1L2'=>array(0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384),
'V1L3'=>array(0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320),
'V2L1'=>array(0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256),
'V2L2'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
'V2L3'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160),
);
static $sample_rates = array(
'1' => array(44100,48000,32000),
'2' => array(22050,24000,16000),
'2.5' => array(11025,12000, 8000),
);
static $samples = array(
1 => array( 1 => 384, 2 =>1152, 3 =>1152, ), //MPEGv1, Layers 1,2,3
2 => array( 1 => 384, 2 =>1152, 3 => 576, ), //MPEGv2/2.5, Layers 1,2,3
);
//$b0=ord($fourbytes[0]);//will always be 0xff
$b1=ord($fourbytes[1]);
$b2=ord($fourbytes[2]);
$b3=ord($fourbytes[3]);
$version_bits = ($b1 & 0x18) >> 3;
$version = $versions[$version_bits];
$simple_version = ($version=='2.5' ? 2 : $version);
$layer_bits = ($b1 & 0x06) >> 1;
$layer = $layers[$layer_bits];
$protection_bit = ($b1 & 0x01);
$bitrate_key = sprintf('V%dL%d', $simple_version , $layer);
$bitrate_idx = ($b2 & 0xf0) >> 4;
$bitrate = isset($bitrates[$bitrate_key][$bitrate_idx]) ? $bitrates[$bitrate_key][$bitrate_idx] : 0;
$sample_rate_idx = ($b2 & 0x0c) >> 2;//0xc => b1100
$sample_rate = isset($sample_rates[$version][$sample_rate_idx]) ? $sample_rates[$version][$sample_rate_idx] : 0;
$padding_bit = ($b2 & 0x02) >> 1;
$private_bit = ($b2 & 0x01);
$channel_mode_bits = ($b3 & 0xc0) >> 6;
$mode_extension_bits = ($b3 & 0x30) >> 4;
$copyright_bit = ($b3 & 0x08) >> 3;
$original_bit = ($b3 & 0x04) >> 2;
$emphasis = ($b3 & 0x03);
$info = array();
$info['Version'] = $version;//MPEGVersion
$info['Layer'] = $layer;
//$info['Protection Bit'] = $protection_bit; //0=> protected by 2 byte CRC, 1=>not protected
$info['Bitrate'] = $bitrate;
$info['Sampling Rate'] = $sample_rate;
$info['Framesize'] = self::framesize($layer, $bitrate, $sample_rate, $padding_bit);
$info['Samples'] = $samples[$simple_version][$layer];
return $info;
}
private static function framesize($layer, $bitrate,$sample_rate,$padding_bit)
{
if ($layer==1)
return intval(((12 * $bitrate*1000 /$sample_rate) + $padding_bit) * 4);
else //layer 2, 3
return intval(((144 * $bitrate*1000)/$sample_rate) + $padding_bit);
}
}
?>
<?php
$mp3file = new MP3File("Chal_Halke.mp3");//http://www.npr.org/rss/podcast.php?id=510282
$duration1 = $mp3file->getDurationEstimate();//(faster) for CBR only
$duration2 = $mp3file->getDuration();//(slower) for VBR (or CBR)
echo "duration: $duration1 seconds"."\n";
?>
There is no native php function to do this.
Depending on your server environment, you may use a tool such as MP3Info.
$length = shell_exec('mp3info -p "%S" sample.mp3'); // total time in seconds
As earlier, I provided a solution for both mp3 and WAV files, Now this solution is specifically for the only WAV file with more precision but with longer evaluation time than the earlier solution.
function calculateWavDuration( $file ) {
$fp = fopen($file, 'r');
if (fread($fp, 4) == "RIFF") {
fseek($fp, 20);
$raw_header = fread($fp, 16);
$header = unpack('vtype/vchannels/Vsamplerate/Vbytespersec/valignment/vbits', $raw_header);
$pos = ftell($fp);
while (fread($fp, 4) != "data" && !feof($fp)) {
$pos++;
fseek($fp, $pos);
}
$raw_header = fread($fp, 4);
$data = unpack('Vdatasize', $raw_header);
$sec = $data[datasize] / $header[bytespersec];
$minutes = intval(($sec / 60) % 60);
$seconds = intval($sec % 60);
return str_pad($minutes, 2, "0", STR_PAD_LEFT) . ":" . str_pad($seconds, 2, "0", STR_PAD_LEFT);
}
}
$file = '1.wav'; //Enter File wav
calculateWavDuration($file);
The MP3 length is not stored anywhere (in the "plain" MP3 format), since MP3 is designed to be "split" into frames and those frames will remain playable.
http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
If you have no ID tag on which to rely, what you would need to do (there are tools and PHP classes that do this) is to read the whole MP3 file and sum the durations of each frame.
$getID3 = new getID3;
$ThisFileInfo = $getID3->analyze($pathName);
// playtime in minutes:seconds, formatted string
$len = #$ThisFileInfo['playtime_string'];
//don't get playtime_string, but get playtime_seconds
$len = #$ThisFileInfo['playtime_seconds']*1000; //*1000 as calculate millisecond
I hope this helps you.
Finally, I developed a solution with my own calculations. This solution works best for mp3 and WAV files formats. However minor precision variations are expected. The solution is in PHP. I take little bit clue from WAV
function calculateFileSize($file){
$ratio = 16000; //bytespersec
if (!$file) {
exit("Verify file name and it's path");
}
$file_size = filesize($file);
if (!$file_size)
exit("Verify file, something wrong with your file");
$duration = ($file_size / $ratio);
$minutes = floor($duration / 60);
$seconds = $duration - ($minutes * 60);
$seconds = round($seconds);
echo "$minutes:$seconds minutes";
}
$file = 'apple-classic.mp3'; //Enter File Name mp3/wav
calculateFileSize($file);
If you have FFMpeg installed, getting the duration is quite simple with FFProbe
$filepath = 'example.mp3';
$ffprobe = \FFMpeg\FFProbe::create();
$duration = $ffprobe->format($filepath)->get('duration');
echo gmdate('H:i:s', $duration);
FFMpeg is mentioned elsewhere, but here's a fuller explanation and example implementation.
Install ffmpeg for your system. E.g., on Ubuntu:
apt-get update && apt-get -y install ffmpeg
Install php-ffmpeg using Composer:
composer require php-ffmpeg/php-ffmpeg
Example utility class
<?php
namespace App\Utils;
use FFMpeg\FFProbe;
class Audio
{
public static function duration(string $path): float
{
$probe = FFProbe::create();
return $probe->format($path)->get('duration');
}
}
Where $path is the absolute path or URL to your audio file. To use:
$duration = \App\Utils\Audio::duration($path);
echo $duration; // 24.476750
Of course, you can just use it directly where you need it. The point of the utility class example is to show how you use it. You'll want to try/catch calling it in a production setting. If you aren't using composer, see #awavi's answer.

PHP: Format Latitude and Longitude with degrees, minuets and seconds

How can I convert this:
26.72773551940918
Into something like this:
22°12'42"N
The trick here is that the coordinates are, actually Latitude and Longitude, I just need to format them correctly.
You can find functions to do that here
<?php
function DMStoDEC($deg,$min,$sec)
{
// Converts DMS ( Degrees / minutes / seconds )
// to decimal format longitude / latitude
return $deg+((($min*60)+($sec))/3600);
}
function DECtoDMS($dec)
{
// Converts decimal longitude / latitude to DMS
// ( Degrees / minutes / seconds )
// This is the piece of code which may appear to
// be inefficient, but to avoid issues with floating
// point math we extract the integer part and the float
// part by using a string function.
$vars = explode(".",$dec);
$deg = $vars[0];
$tempma = "0.".$vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min*60);
return array("deg"=>$deg,"min"=>$min,"sec"=>$sec);
}
?>
The lat/lon coords are written in (roughly speaking) a base-60 numeral system. Here's how you convert them:
function fraction_to_min_sec($coord)
{
$isnorth = $coord>=0;
$coord = abs($coord);
$deg = floor($coord);
$coord = ($coord-$deg)*60;
$min = floor($coord);
$sec = floor(($coord-$min)*60);
return array($deg, $min, $sec, $isnorth ? 'N' : 'S');
// or if you want the string representation
return sprintf("%d°%d'%d\"%s", $deg, $min, $sec, $isnorth ? 'N' : 'S');
}
I say my function has better numerical stability than #SeRPRo's one.
Here's one where you pass in the latitude,longitude in DMS values and returns the converted DMS string. Easy and simple
function DECtoDMS($latitude, $longitude)
{
$latitudeDirection = $latitude < 0 ? 'S': 'N';
$longitudeDirection = $longitude < 0 ? 'W': 'E';
$latitudeNotation = $latitude < 0 ? '-': '';
$longitudeNotation = $longitude < 0 ? '-': '';
$latitudeInDegrees = floor(abs($latitude));
$longitudeInDegrees = floor(abs($longitude));
$latitudeDecimal = abs($latitude)-$latitudeInDegrees;
$longitudeDecimal = abs($longitude)-$longitudeInDegrees;
$_precision = 3;
$latitudeMinutes = round($latitudeDecimal*60,$_precision);
$longitudeMinutes = round($longitudeDecimal*60,$_precision);
return sprintf('%s%s° %s %s %s%s° %s %s',
$latitudeNotation,
$latitudeInDegrees,
$latitudeMinutes,
$latitudeDirection,
$longitudeNotation,
$longitudeInDegrees,
$longitudeMinutes,
$longitudeDirection
);
}
Here is the opposite when you have DMS string and need it as float number (contains unicode characters):
//e.g.
$dec = dms_to_dec("-18° 51' 30.5697\"");
/**
* Convert a coordinate in dms to dec
*
* #param string $dms coordinate
* #return float
*/
function dms_to_dec($dms)
{
$dms = stripslashes($dms);
$neg = (preg_match('/[SWO]/i', $dms) == 0) ? 1 : -1;
$dms = preg_replace('/(^\s?-)|(\s?[NSEWO]\s?)/i', '', $dms);
$pattern = "/(\\d*\\.?\\d+)(?:[°ºd: ]+)(\\d*\\.?\\d+)*(?:['m′: ])*(\\d*\\.?\\d+)*[\"s″ ]?/i";
$parts = preg_split($pattern, $dms, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if (!$parts) {
return;
}
// parts: 0 = degree, 1 = minutes, 2 = seconds
$d = isset($parts[0]) ? (float)$parts[0] : 0;
$m = isset($parts[1]) ? (float)$parts[1] : 0;
if (strpos($dms, ".") > 1 && isset($parts[2])) {
$m = (float)($parts[1] . '.' . $parts[2]);
unset($parts[2]);
}
$s = isset($parts[2]) ? (float)$parts[2] : 0;
$dec = ($d + ($m/60) + ($s/3600))*$neg;
return $dec;
}

PHP extract GPS EXIF data

I would like to extract the GPS EXIF tag from pictures using php.
I'm using the exif_read_data() that returns a array of all tags + data :
GPS.GPSLatitudeRef: N
GPS.GPSLatitude:Array ( [0] => 46/1 [1] => 5403/100 [2] => 0/1 )
GPS.GPSLongitudeRef: E
GPS.GPSLongitude:Array ( [0] => 7/1 [1] => 880/100 [2] => 0/1 )
GPS.GPSAltitudeRef:
GPS.GPSAltitude: 634/1
I don't know how to interpret 46/1 5403/100 and 0/1 ? 46 might be 46° but what about the rest especially 0/1 ?
angle/1 5403/100 0/1
What is this structure about ?
How to convert them to "standard" ones (like 46°56′48″N 7°26′39″E from wikipedia) ? I would like to pass thoses coordinates to the google maps api to display the pictures positions on a map !
This is my modified version. The other ones didn't work for me. It will give you the decimal versions of the GPS coordinates.
The code to process the EXIF data:
$exif = exif_read_data($filename);
$lon = getGps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
$lat = getGps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
var_dump($lat, $lon);
Prints out in this format:
float(-33.8751666667)
float(151.207166667)
Here are the functions:
function getGps($exifCoord, $hemi) {
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
}
function gps2Num($coordPart) {
$parts = explode('/', $coordPart);
if (count($parts) <= 0)
return 0;
if (count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
This is a refactored version of Gerald Kaszuba's code (currently the most widely accepted answer). The result should be identical, but I've made several micro-optimizations and combined the two separate functions into one. In my benchmark testing, this version shaved about 5 microseconds off the runtime, which is probably negligible for most applications, but might be useful for applications which involve a large number of repeated calculations.
$exif = exif_read_data($filename);
$latitude = gps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
$longitude = gps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
function gps($coordinate, $hemisphere) {
if (is_string($coordinate)) {
$coordinate = array_map("trim", explode(",", $coordinate));
}
for ($i = 0; $i < 3; $i++) {
$part = explode('/', $coordinate[$i]);
if (count($part) == 1) {
$coordinate[$i] = $part[0];
} else if (count($part) == 2) {
$coordinate[$i] = floatval($part[0])/floatval($part[1]);
} else {
$coordinate[$i] = 0;
}
}
list($degrees, $minutes, $seconds) = $coordinate;
$sign = ($hemisphere == 'W' || $hemisphere == 'S') ? -1 : 1;
return $sign * ($degrees + $minutes/60 + $seconds/3600);
}
According to http://en.wikipedia.org/wiki/Geotagging, ( [0] => 46/1 [1] => 5403/100 [2] => 0/1 ) should mean 46/1 degrees, 5403/100 minutes, 0/1 seconds, i.e. 46°54.03′0″N. Normalizing the seconds gives 46°54′1.8″N.
This code below should work, as long as you don't get negative coordinates (given that you get N/S and E/W as a separate coordinate, you shouldn't ever have negative coordinates). Let me know if there is a bug (I don't have a PHP environment handy at the moment).
//Pass in GPS.GPSLatitude or GPS.GPSLongitude or something in that format
function getGps($exifCoord)
{
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
//normalize
$minutes += 60 * ($degrees - floor($degrees));
$degrees = floor($degrees);
$seconds += 60 * ($minutes - floor($minutes));
$minutes = floor($minutes);
//extra normalization, probably not necessary unless you get weird data
if($seconds >= 60)
{
$minutes += floor($seconds/60.0);
$seconds -= 60*floor($seconds/60.0);
}
if($minutes >= 60)
{
$degrees += floor($minutes/60.0);
$minutes -= 60*floor($minutes/60.0);
}
return array('degrees' => $degrees, 'minutes' => $minutes, 'seconds' => $seconds);
}
function gps2Num($coordPart)
{
$parts = explode('/', $coordPart);
if(count($parts) <= 0)// jic
return 0;
if(count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
I know this question has been asked a long time ago, but I came across it while searching in google and the solutions proposed here did not worked for me. So, after further searching, here is what worked for me.
I'm putting it here so that anybody who comes here through some googling, can find different approaches to solve the same problem:
function triphoto_getGPS($fileName, $assoc = false)
{
//get the EXIF
$exif = exif_read_data($fileName);
//get the Hemisphere multiplier
$LatM = 1; $LongM = 1;
if($exif["GPSLatitudeRef"] == 'S')
{
$LatM = -1;
}
if($exif["GPSLongitudeRef"] == 'W')
{
$LongM = -1;
}
//get the GPS data
$gps['LatDegree']=$exif["GPSLatitude"][0];
$gps['LatMinute']=$exif["GPSLatitude"][1];
$gps['LatgSeconds']=$exif["GPSLatitude"][2];
$gps['LongDegree']=$exif["GPSLongitude"][0];
$gps['LongMinute']=$exif["GPSLongitude"][1];
$gps['LongSeconds']=$exif["GPSLongitude"][2];
//convert strings to numbers
foreach($gps as $key => $value)
{
$pos = strpos($value, '/');
if($pos !== false)
{
$temp = explode('/',$value);
$gps[$key] = $temp[0] / $temp[1];
}
}
//calculate the decimal degree
$result['latitude'] = $LatM * ($gps['LatDegree'] + ($gps['LatMinute'] / 60) + ($gps['LatgSeconds'] / 3600));
$result['longitude'] = $LongM * ($gps['LongDegree'] + ($gps['LongMinute'] / 60) + ($gps['LongSeconds'] / 3600));
if($assoc)
{
return $result;
}
return json_encode($result);
}
This is an old question but felt it could use a more eloquent solution (OOP approach and lambda to process the fractional parts)
/**
* Example coordinate values
*
* Latitude - 49/1, 4/1, 2881/100, N
* Longitude - 121/1, 58/1, 4768/100, W
*/
protected function _toDecimal($deg, $min, $sec, $ref) {
$float = function($v) {
return (count($v = explode('/', $v)) > 1) ? $v[0] / $v[1] : $v[0];
};
$d = $float($deg) + (($float($min) / 60) + ($float($sec) / 3600));
return ($ref == 'S' || $ref == 'W') ? $d *= -1 : $d;
}
public function getCoordinates() {
$exif = #exif_read_data('image_with_exif_data.jpeg');
$coord = (isset($exif['GPSLatitude'], $exif['GPSLongitude'])) ? implode(',', array(
'latitude' => sprintf('%.6f', $this->_toDecimal($exif['GPSLatitude'][0], $exif['GPSLatitude'][1], $exif['GPSLatitude'][2], $exif['GPSLatitudeRef'])),
'longitude' => sprintf('%.6f', $this->_toDecimal($exif['GPSLongitude'][0], $exif['GPSLongitude'][1], $exif['GPSLongitude'][2], $exif['GPSLongitudeRef']))
)) : null;
}
The code I've used in the past is something like (in reality, it also checks that the data is vaguely valid):
// Latitude
$northing = -1;
if( $gpsblock['GPSLatitudeRef'] && 'N' == $gpsblock['GPSLatitudeRef'] )
{
$northing = 1;
}
$northing *= defraction( $gpsblock['GPSLatitude'][0] ) + ( defraction($gpsblock['GPSLatitude'][1] ) / 60 ) + ( defraction( $gpsblock['GPSLatitude'][2] ) / 3600 );
// Longitude
$easting = -1;
if( $gpsblock['GPSLongitudeRef'] && 'E' == $gpsblock['GPSLongitudeRef'] )
{
$easting = 1;
}
$easting *= defraction( $gpsblock['GPSLongitude'][0] ) + ( defraction( $gpsblock['GPSLongitude'][1] ) / 60 ) + ( defraction( $gpsblock['GPSLongitude'][2] ) / 3600 );
Where you also have:
function defraction( $fraction )
{
list( $nominator, $denominator ) = explode( "/", $fraction );
if( $denominator )
{
return ( $nominator / $denominator );
}
else
{
return $fraction;
}
}
To get the altitude value, you can use the following 3 lines:
$data = exif_read_data($path_to_your_photo, 0, TRUE);
$alt = explode('/', $data["GPS"]["GPSAltitude"]);
$altitude = (isset($alt[1])) ? ($alt[0] / $alt[1]) : $alt[0];
In case you need a function to read Coordinates from Imagick Exif here we go, I hope it saves you time. Tested under PHP 7.
function create_gps_imagick($coordinate, $hemi) {
$exifCoord = explode(', ', $coordinate);
$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
}
function gps2Num($coordPart) {
$parts = explode('/', $coordPart);
if (count($parts) <= 0)
return 0;
if (count($parts) == 1)
return $parts[0];
return floatval($parts[0]) / floatval($parts[1]);
}
I'm using the modified version from Gerald Kaszuba but it's not accurate.
so i change the formula a bit.
from:
return $flip * ($degrees + $minutes / 60);
changed to:
return floatval($flip * ($degrees +($minutes/60)+($seconds/3600)));
It works for me.
This is a javascript port of the PHP-code posted #Gerald above. This way you can figure out the location of an image without ever uploading the image, in conjunction with libraries like dropzone.js and Javascript-Load-Image
define(function(){
function parseExif(map) {
var gps = {
lng : getGps(map.get('GPSLongitude'), data.get('GPSLongitudeRef')),
lat : getGps(map.get('GPSLatitude'), data.get('GPSLatitudeRef'))
}
return gps;
}
function getGps(exifCoord, hemi) {
var degrees = exifCoord.length > 0 ? parseFloat(gps2Num(exifCoord[0])) : 0,
minutes = exifCoord.length > 1 ? parseFloat(gps2Num(exifCoord[1])) : 0,
seconds = exifCoord.length > 2 ? parseFloat(gps2Num(exifCoord[2])) : 0,
flip = (/w|s/i.test(hemi)) ? -1 : 1;
return flip * (degrees + (minutes / 60) + (seconds / 3600));
}
function gps2Num(coordPart) {
var parts = (""+coordPart).split('/');
if (parts.length <= 0) {
return 0;
}
if (parts.length === 1) {
return parts[0];
}
return parts[0] / parts[1];
}
return {
parseExif: parseExif
};
});
short story.
First part N
Leave the grade
multiply the minutes with 60
devide the seconds with 100.
count the grades,minuts and seconds with eachother.
Second part E
Leave the grade
multiply the minutes with 60
devide the seconds with ...1000
cöunt the grades, minutes and seconds with each other
i have seen nobody mentioned this: https://pypi.python.org/pypi/LatLon/1.0.2
from fractions import Fraction
from LatLon import LatLon, Longitude, Latitude
latSigned = GPS.GPSLatitudeRef == "N" ? 1 : -1
longSigned = GPS.GPSLongitudeRef == "E" ? 1 : -1
latitudeObj = Latitude(
degree = float(Fraction(GPS.GPSLatitude[0]))*latSigned ,
minute = float(Fraction(GPS.GPSLatitude[0]))*latSigned ,
second = float(Fraction(GPS.GPSLatitude[0])*latSigned)
longitudeObj = Latitude(
degree = float(Fraction(GPS.GPSLongitude[0]))*longSigned ,
minute = float(Fraction(GPS.GPSLongitude[0]))*longSigned ,
second = float(Fraction(GPS.GPSLongitude[0])*longSigned )
Coordonates = LatLon(latitudeObj, longitudeObj )
now using the Coordonates objecct you can do what you want:
Example:
(like 46°56′48″N 7°26′39″E from wikipedia)
print Coordonates.to_string('d%°%m%′%S%″%H')
You than have to convert from ascii, and you are done:
('5\xc2\xb052\xe2\x80\xb259.88\xe2\x80\xb3N', '162\xc2\xb04\xe2\x80\xb259.88\xe2\x80\xb3W')
and than printing example:
print "Latitude:" + Latitude.to_string('d%°%m%′%S%″%H')[0].decode('utf8')
>> Latitude: 5°52′59.88″N

Categories