0

I want to check if a remote file has changed before saving it to my server. First I've checked if the file exists before executing a comparison using md5_file between the remote file and the local file, but this is really slow. Is there a faster way to check this?

$channelName = htmlspecialchars($_GET['channel'], ENT_QUOTES);

$json_array = json_decode(file_get_contents('http://api.hitbox.tv/media/live/'.strtolower($channelName)), true);
$getImage = $json_array['livestream'][0]['channel']['user_logo_small'];
$imageURL = "http://edge.vie.hitbox.tv/$getImage";
$imagePath = str_replace("/static/img/channel/", "", $getImage);
$ImageExtension = substr( strrchr($imagePath, '.'), 1);
$imageOutput = "images/$channelName.".$ImageExtension;

if (file_exists($imageOutput)) {

  if (md5_file($imageURL) != md5_file($imageOutput)) {
    file_put_contents($imageOutput, file_get_contents($imageURL));
  }

} else {
  file_put_contents($imageOutput, file_get_contents($imageURL));
}

Maybe someone can help me out a bit or lead me into the right direction ^^

Kind regards, Kazuto

skaffman
  • 398,947
  • 96
  • 818
  • 769
Kazuto
  • 158
  • 2
  • 15
  • To begin with, you could check if the two files have different size. If they do, you know md5-ing them will give different results, and the file has changed. Also, I would believe comparing the files byte by byte is quicker than md5. – Suppen Apr 04 '15 at 10:03
  • 1
    This is a solved problem in http - use the information in the header returned by the remote server previously (last-modified, etag) to create a conditional request and ASK if it has changed (remote server will respond with 304 if unchanged) – symcbean Apr 04 '15 at 10:25
  • Thanks @Suppen. I haven't thought about comparing the filesizes. Comparing them should be enough, since they're only around 3kb large. – Kazuto Apr 04 '15 at 11:44

1 Answers1

0

I have used Pack and Unpack function to do something similar. Was converting image and pdf file to binary rather than md5. I am not sure about performance compare to MD5 but its good to take a look at it.

http://php.net/manual/en/function.pack.php

http://php.net/manual/en/function.unpack.php

shivanshu patel
  • 782
  • 10
  • 19