Friday, January 25, 2013

Read image metadata using PHP

How to read image Metadata using PHP?

This article explains you how to read image Metadata using PHP programming language
Read image meta data using php exif function

What is image Metadata?

Image Metadata refers to piece of information that stored in a photo. These information are automatically embedded to the digital image when it was created. Usually digital cameras, iPhones, Smart phones, and other phones can store these kind of data in the captured image. Stored data can be varies from camera to camera. You have refer manufactures manuals to see what kind of data it can be stored in the image using the device. However there are some common data that stored in each and every image while they were capturing. These Meta data are stored in the headers of the images files such as jpg, jpeg, png, etc. You can use these Meta data to identify images. -eta data are like DNA's of a digital image. They knows everything of the image.

Image Meta data contains following information in its headers.

  • Date of Captured.
  • Image Dimensions (width and height in pixels).
  • Horizontal and Vertical Resolution of the image (96 dpi).
  • Bit Depth (24).
  • Color Representation (e.g. sRGB).
  • Camera Model. (e.g. iPhone 4s)
  • Camera Maker (e.g. Apple)
  • Exposure Time (e.g. 1/15 sec.)
  • F-stop (f/2.4)
  • ISO Speed (ISO-640)
  • Focal Length (4mm)
  • EXIF Version (0221)
  • Longitude (7;52;45)
  • Latitude (6;48;21.454)
  • Altitude (21)
  • Item Type (in images jpg or png)
  • File Size
  • Owner.

Above Metadata are common in most images. But there are lot of other information that can embedded in the digital images. Those information are differ from device to device. So there can be dozens of individual Meta data properties in the captured image. You can read those information using PHP exif library.

Importance of image Metadata.

You can use image Metadata to identify various information about the media; such as the author of the image, when it was taken, where it taken from, what is the camera model, copyright information, etc. Copyright information are important for the ownership. GPS data (latitude, longitude, and altitude) are useful to find the location of the photo. GPS data also important to SEO purposes. They are help to search engines to find the relevant images. Image dimensions, bit depth, resolution, image size, image type are useful when dealing with images. The applications that use to edit images such as Photoshop, CorelDraw reads these Meta data to identify the the image.


What is Exif?

Exif stands for Exchangeable image file format. It is maintained by Camera and Imaging Products Association (CIPA). And published by Japan Electronics and Information Technology Industries Association (JEITA). Exif is a standard that describes the formats for images and tags used by digital cameras. It also contains the technical information about the captured image, Exif data are stored in image headers and does not directly visible to the viewer. You have to use special methods to manipulate and read exif data.

How to read Exif data using PHP?

PHP has a extension to deal with image files. it has functions to read Metadata of the image. Before you read the exif data through the PHP exif library, you have to do some configuration to your PHP installation.

Step 1: Enable php_mbstring and php_exif extensions in your php.ini file (PHP configuration file) To do this open your php.ini file and remove the semicolon in font of the extension.

Step 2: Restart Apache web server.

You have to keep in mind the order of the mbstring and exif libraries in the php.ini file. mbstring extension must be loaded before the php_exif extension. Otherwise you may get errors like follows.

"Fatal error: Call to undefined function exif_imagetype() in D:\Projects\read-image-meta-data\exif.php on line 3" -> Solution: enable php_mbstring.dll and php_exif.dll extension respectively in the php.ini file.

Now you are ready to read image Meta data using PHP exif library. Following examples show how to do it.

1. How to get the image type in PHP?

You can use exif_imagetype() function to determine the type of the image. It returns a integer value corresponding to the image type. If it fails to determine the image type it returns FALSE. Common image type constants are IMAGETYPE_JPEG (2), IMAGETYPE_PNG (3), IMAGETYPE_GIF(1), and IMAGETYPE_BMP (6). Likewise there are many other image file type constants defined in PHP. Please refer the manual. Instead of using image constants, you can also use relevant integer value for the switch cases. Following example shows you how to determine image type by reading exif data in PHP.

<?php
$image_file = 'D:\Photoes\2013\IMG_0213.jpg';
$image_type='';

if(file_exists($image_file)){
$type = exif_imagetype($image_file);

switch($type){
case IMAGETYPE_GIF:{
$image_type = 'GIF';
}break;
case IMAGETYPE_JPEG:{
$image_type = 'JPEG';
}break;
case IMAGETYPE_PNG:{
$image_type = 'PNG';
}break;
case IMAGETYPE_BMP:{
$image_type = 'BMP';
}break;
default:{
$image_type = 'Not gif,jpeg,png,or bmp';
};
}
echo 'Image type is '.$image_type;
}else{
echo 'File does not exists';
}

?>

2. How to read exif image headers using php?

exif_read_data() function reads the exif headers of a image file. This method returns an array of Meta data related to the image. Return details can be differ from camera to camera. Returned array is an associative array with header names as indexes. If no data found it returns FALSE. Following example prints all exif information of a given image.

<?php
$image_file = 'D:\Photoes\2012\DSC02710.JPG';
$image_type='';

$tab=str_repeat('&nbsp;',12);
if(file_exists($image_file)){
$details=exif_read_data($image_file);
foreach($details as $key=>$val){
echo $key.' = '.$val.'<br/>';
if(is_array($val)){
foreach($val as $key2=>$val2){
echo "<span style=\"margin-left:30px;\">".$key2.' = '.$val2.'</span><br/>';
}
}
}
}else{
echo 'File does not exists';
}

?>

3. Read image Meta data information more..

Sometimes you may be need to get the date that the photo was taken, Camera Model and Make, ISO Speed Ratings, GPS data, file size, resolution, width and height, and so on. Please refer following sample codes/scripts to read image Meta data. Some of these may not work with older images. But now most digital cameras embedded more image details with the produced image. So it is good practice to check your code with images which are taken from different camera models.

<?php
$image_file = 'D:\Photoes\2011\19062011433.jpg';

if(file_exists($image_file)){
$details = exif_read_data($image_file);
}else{
die('File does not exists');
}
?>

Please note that I have use above $details array for following examples. So you have to define it at the top of your script.

(a). How to get file name and file size using exif data?

echo 'File name is '.$details['FileName'].' and size is '.number_format(($details['FileSize']/1024),2).' Kb';

(b). How to get image create date time using php?

echo $details['DateTimeOriginal'];

(c). How to get camera model and make in php?

echo 'Make is '.$details['Make'].' and model is '.$details['Model'];

(d).How to get mime type using exif image data?

echo 'Mime type is '.$details['MimeType'];

(e). How to find image width and height using php exif details?

echo 'Height = '.$details['COMPUTED']['Height'].'px and Width = '.$details['COMPUTED']['Width'].'px';

or you can use following code.

echo 'Width = '.$details['ExifImageWidth'].'px Height = '.$details['ExifImageLength'];

4. How to read GPS data of an image taken from a digital camera?

GPS data helps to identify the where the image is taken from. It is useful load image location in a Google Map. You can use these latitude and longitude to create a Google Map. Most of latest digital cameras,smart phone cameras, and mobile phone cameras embedded the GPS data in to images taken. Please refer following examples. Before you read exif GPS data, please make sure your camera supports for automatic location tagging (geotagging) of images and videos. In the exif data array there is a key named 'SectionsFound'. First of all you have to check GPS section is included in it. If GPS section exists you can make sure that photo contains GPS data such as latitude and longitude.

<?php
$image_file = 'D:\Photoes\2011\IMG_0712.jpg';

if(file_exists($image_file)){
$details = exif_read_data($image_file);
$sections = explode(',',$details['SectionsFound']);

if(in_array('GPS',array_flip($sections))){
echo format_gps_data($details['GPSLatitude'],$details['GPSLatitudeRef']);
echo '<br/>';
echo format_gps_data($details['GPSLongitude'],$details['GPSLongitudeRef']);
}else{
die('GPS data not found');
}
}else{
die('File does not exists');
}

function format_gps_data($gpsdata,$lat_lon_ref){
$gps_info = array();
foreach($gpsdata as $gps){
list($j , $k) = explode('/', $gps);
array_push($gps_info,$j/$k);
}
$coordination = $gps_info[0] + ($gps_info[1]/60.00) + ($gps_info[2]/3600.00);
return (($lat_lon_ref == "S" || $lat_lon_ref == "W" ) ? '-'.$coordination : $coordination).' '.$lat_lon_ref;
}


?>

Thursday, January 10, 2013

Generate random numbers in php

How to generate random numbers using PHP?

The following example explains you how to generate random numbers in php
Random Numbers are very common in our day today life. For an example think of a dice game or a lottery game. When drawing a lottery, there is a lottery machine that use to draw the winning numbers. It has the feature of random selection of lotto balls. It is difficult to predict what are the winning numbers till the end. Because it produce a random combination of numbers. But we can guess the the selection will be between 1 and 99 (for example. some times there are set of duplicate set of lotto balls for a draw.). Likewise we can generate random numbers between given two numbers using PHP.

PHP Random number generator

Random number generation methods

  1. Physical Methods
  2. Computational methods

Physical methods are earliest methods that used to generate random numbers. Coin flipping, dice throwing are examples for physical methods. Computational methods use mathematical algorithms to populate random numbers. Physical methods are very slow.

You can use rand(), or mt_rand() functions to generate random numbers in php


rand() function returns an integer value as a random number. Also you can specify lower and upper limit for generated number. also you can get the largest random number can be generated using rand() function. rand() function is 4 times slower than mt_rand(). So it is better to use mt_rand() method to make random numbers in php. Also mt_rand() produce bigger random value comparing to the rand() method. Usually it will be equal to maximum size of the integer value that can be produce by the system. maximum integer value is platform dependent.

Usage of random numbers

  1. Prepare online MCQ papers. (use to provide a random set of questions from a set of questions).
  2. Games (ex. dice, coin).
  3. Show selected posts (e.g. display Random posts in your website).
  4. Shuffle a play list.
  5. Generate CAPTCHA verification images.
  6. Create random passwords.
  7. Prevent caching web pages. (e.g. When using ajax calls append a random number at the end of the URL)

1. How to generate random numbers using php?

<?php
echo rand();//traditional pseudo-random number

echo '<br/>';

echo mt_rand();//Generate better random number. This is the newest method
?>

You can use above sample code to generate random integers in php. rand() function produce a small value than mt_rand(). All generated random numbers in the range of 0 to max random number that can be generated by the system.

2. How to determine maximum random values that can be generated using php?

<?php
echo getrandmax(); /* Maximum random value that can be generate using rand() method
This will out put 32767 in windows 7 - 32 bit computer */


echo '<br/>';

echo mt_getrandmax(); /* Maximum random value that can be generated using mt_rand() method This will out put 2147483647 in windows 7 - 32 bit machine */
?>

Maximum random number that can be generated by the system is platform dependent. It returns the largest possible integer value that can be return by rand() or mt_rand() function. Usually this is equal to the maximum integer value of your system. This also platform dependant. You can find the maximum integer value as follows.

<?php
echo PHP_INT_MAX;//maximum possible integer value
?>

3. How to generate a random number within a specific range in php?

<?php
$min = 10; // The lowest value of the random number to generate
$max = 100; // The maximum value to generate

echo rand($min,$max); /* Generate random number between 10 and 100*/

echo '<br/>';

echo mt_rand($min,$max); /* Get random value between 10 and 100 */
?>

Suppose that you need to generate random numbers between specific range, you can do it by passing minimum and maximum values to the rand() or mt_rand() functions. Then the generated random integers will be in the range that you have provide. By default minimum random number is 0 and the maximum random number is getrandmax() or mt_getrandmax() value. Maximum random numbers are platform dependent.

4. PHP random number examples

Think that you have to generate 10 random numbers between 1 and 100. Also you have to count the number of times each number generated. Also you need to print the summary of each occurrence Following example describes you how to do it.

<?php
$random_numbers =array();
for($x=0;$x<10;$x++){
$rnd = mt_rand(1,100);
if(array_key_exists($rnd,$random_numbers)){
$random_numbers[$rnd]++;
}else{
$random_numbers[$rnd]=1;
}
}

foreach($random_numbers as $number=>$times){
echo 'Number '.$number.' was generated '.$times.' times(s)<br/>';
}
?>

Random numbers are very useful. As a example you have a play list with 20 songs. What you have to do is play randomly selected songs of re arrange/shuffle the play list. You can use random numbers to perform the task.

Following example shows you how to select a day of the week randomly using php.

<?php
$days=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
echo $days[mt_rand(0,count($days)-1)];
?>

Bellow example describes you how to generate random numbers 1 to 100

<?php
echo mt_rand(1,100);
?>

Saturday, January 5, 2013

redirect url using javascript

How to redirect URL in JavaScript?

Following examples shows you how load another URL using JavaScript.

When you are working with JavaScript, sometimes you may need to redirect the user to another page. As an example you have a user login form implemented using Ajax. After user enter correct user name and password, you have to redirect the user to user profile page or index page. You can use JavaScript Location object to perform the task.

window.location methods,

window.location.assign('url') - this will load a new document to the browser.
window.location.reload('true/false') - this will reload the current document.
window.location.replace('url') - load new page to the browser window.

When dealing with URL redirect you can use Location object. It has details of the current URL in your browser window. It is a property of the JavaScript window object. This article describes you how to do JavaScript redirect in different ways.
.

1. Example code- Simple JavaScript URL redirect.

<script type="text/javascript">
var URLToRedirect='http://www.latestcode.net';
window.location=URLToRedirect;
</script>

Live Demo -URL Redirection
URL to redirect
Redirect

What you have to do is simply assign the URL that you need to redirect to the window.location object. You can type any URL in the provided text box and check the redirect by click on "Redirect" button. Please make sure that you have to enter the URL in correct format. otherwise it will not work properly. If you want to redirect to another domain always use http://(Protocol) to the URL parameter. But you don't need to add http:// (Protocol) part to the URL redirect with locations in the same domain.

As a example, suppose that you have to redirect the user to different domain use following script.

window.location.href='http://www.facebook.com';

If you need to redirect the user to the file in the same domain use following code to do that. As an example you have a list of news items in a page. You need to redirect the user to each detailed news item after the user clicks on "more' button.

window.location.href='/news/10-more.html';

2. Other ways to do the JavaScript redirect.

javascript url redirection example

<script type="text/javascript">

var URLToRedirect='http://goo.gl/0WEKV';
window.location.href=URLToRedirect;
</script>

In here we have assign the redirection url to the href property of the location object. This is similar to click on a link to go to a new page. This will redirect you to new web page from your current page. In here if you click on browser's back button, you can again go to the previous page. That means you can use javascript history back function to go to previous page.

<script type="text/javascript">
var URLToRedirect='http://goo.gl/fgzu4';
window.location.replace(URLToRedirect);
</script>

This example shows you URL redirection using location.replace() method. It replace the current document with the given URL. In here you can't go to the previous page by clicking browser's back button. So it is not included in browser's history. In other words you can't use javascript history back method to go to the previous page that you have visited.

3. How to reload the page using JavaScript?

<script type="text/javascript">
function leload_page(){
window.location.reload(); //reload from cache folder
}
</script>

Demo - JavaScript Page Reload

Reload This Page


Also you can use location.reload() method to reload the current document. This is similar to click browser's reload button. By default page will be reloaded from the browser cache. But you can force to reload it from the server by passing the parameter forceGet as true. It is similar to click ctrl+F5. What you have to do is simply pass true or false to reload() method.

<script type="text/javascript">
function leload_page(){
window.location.reload(true); //reload from server
}
</script>

You can test this reload function by creating a simple HTML page with an image. Also you have to install firebug on your browser. First reload the page from cache and check http status. You can see 304 Not Modified. That means the page load from your browser's cache. Then use the forceGet parameter true for reload document from the web server. Again check the http status. It shows the 200 OK.


Reload page from cache and server

4. Use JavaScript Location object for navigate to URLs (More Examples).

Also you can use location.assign() method to navigate to another link using JavaScript. It loads a new document to your browser window. This method supports browser back button. In other words you can come back to previous page by clicking browser's back button.

<script type="text/javascript">
var URLToRedirect='http://goo.gl/0WEKV';
window.location.assign(URLToRedirect);
</script>

Also you can redirect the user to a new page using self.location. See how it works.

<script type="text/javascript">
var new_page='http://goo.gl/0WEKV';
self.location=new_page;
</script>

There is an another way for do the redirection. Here you can use top.location to redirect the page. Try bellow example.

<script type="text/javascript">
var new_page='http://goo.gl/0WEKV';
top.location=new_page;
</script>