PHP

Here's a little script I just cooked up for my crontab. It watches the sites listed in the URLs array for changes in the "plain text"; when a change is detected, it outputs the URL.

Although the task is somewhat trivial, this script does a good job of demonstrating how convenient bound parameters can be. To make the update, I simply need to call $upd->execute(). No need to manipulate or massage the variables in the script, and no need to generate the SQL statement on each iteration.

<?php   
   $URLS = array(
      'http://www.nvidia.com/object/linux.html',
      'http://ipw2200.sourceforge.net/news.php',
   );
   if (!extension_loaded('pdo_sqlite')) {
      dl('pdo.so');
      dl('pdo_sqlite.so');
   }
   $db = new PDO('sqlite:' . getenv('HOME') . "/.web-watch.sql3");
   $db->query('create table hash(url primary key, hash)');
   $db->setAttribute(PDO_ATTR_ERRMODE, PDO_ERRMODE_EXCEPTION);
   $cached_hash = null;
   $stmt = $db->prepare('select hash from hash where url = :url');
   $stmt->bindParam(':url', $url);
   $stmt->bindColumn('hash', $cached_hash);
   $upd = $db->prepare('replace into hash (url, hash) values (:url, :hash)');
   $upd->bindParam(':url', $url);
   $upd->bindParam(':hash', $hash);
   foreach ($URLS as $url) {
      $body = file_get_contents($url);
      $hash = md5(strip_tags($body));
      $cached_hash = null;
      if ($stmt->execute()) {
         $stmt->fetch(PDO_FETCH_BOUND);
      }
      if ($cached_hash != $hash) {
         $upd->execute();
         echo "Changed web:\\n$url\\n";
      }
   }
?>

View Comments