PHP Image or Video duplicate check with MySQL

It is easier to check duplicate or changed file like images, videos, text files and so on.

Syntax

$sha_hash = sha1_file(file_path);
  • sha1_file() is using the US Secure Hash Algorithm 1
  • it procudes 160-bit output contains 40 character hash.
Example 1
$sha1_sheep = sha1_file('images/sheep.jpg');
$sha1_duck = sha1_file('images/duck.jpg');

if($sha1_sheep == $sha1_duck) {
    echo 'Images are Identical';
} else {
    echo 'Images are Not Identical';
}
Output
sha1_file of sheep : 1d12e1f1b22230c08f0cdeedd636ad85e5300779
sha1_file of duck  : b2b451a614df36981e240c608846dbb7761cac9d

Images are Not Identical
From the previous example, it compared two images sha1 hash to check both are same.

Example 2
Here, we can use MySQL database to check whether we have uploaded the same image already. It will find out duplicate content and reduces space in server.
 
MySql Table image_hash
image_url sha1_hash
sheep.jpg a6d767d7937359e7836553e6cbe8face074d1d2d
duck.jpg 0410975621226af6847d84a66c0fe7459cb82006
cow.jpg 56599501194bd771b93ffae58a61460e500eba4d
puppy.jpg 5eed2f2bfcbcb40494e3f1f82118746549638b83
horse.jpg d48d77bd375f2056c80b152a6138065c5c5fefdd
 
$file = 'puppy.jpg';
$sha1_hash = sha1_file($file);

$query = $pdo->query("SELECT COUNT(*) FROM image_hash WHERE sha1_hash='$sha1_hash'");
$row = $query->fetch();
$count = $row[0];

if($count == 0) {
    #insert query for new image
    $pdo->query("INSERT INTO image_hash SET image_url='$file', sha1_hash='$sha1_hash'");
    #further process..
} else {
    #duplicate image found..
    echo 'It is a duplicate Image';
    #further duplicate image handling process over here..
}
PHP MySQL Files Posted on 2016-04-17 05:35:42