Automatic “latest version” link

If you have software that you version and want to have a single link that will always download the latest version, here is a way to do that.

We create installers with the naming convention <product name>_major.minor.build.pkg or exe. For example, SiliconConnectorForBoxCC_2.0.12.pkg. I created a php script that would parse the files it finds and return the latest version.

<?php
/**
 * latestmac.php
 * Returns the file with the latest version number.
 * IMPORTANT: Assumes filename_1.2.3.pkg format, meaning
 * an underscore separates the version from the rest,
 * and it has .pkg (4 characters) after the version.
 */

$files1 = scandir(".");
$file_read = ["pkg"];
$filearray = [];

function compareVersions($file1, $file2) {
 $version1 = substr(explode('_', $file1)[1], 0, -4);
 $version2 = substr(explode('_', $file2)[1], 0, -4);
 return version_compare($version1, $version2);
}

foreach ($files1 as $key => $value) {
 if (!in_array($value, array('.', '..'))) {
  $type = explode('.', $value);
  $type = array_reverse($type);
  if (in_array($type[0], $file_read)) {
   $filearray[] = $value;
  }
 }
}

uasort($filearray, 'compareVersions');
$filename = $filearray[sizeof($filearray)-1];

if (file_exists($filename)) {
 header('Pragma: public');
 header('Expires: 0');
 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
 header('Cache-Control: private', false); // required for certain browsers
 header('Content-Type: application/octet-stream');
 header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
 header('Content-Length: ' . filesize($filename));
 readfile($filename);
 exit;
}

?>

Visiting the url (i.e., example.com/downloads/latestmac.php) will trigger the file to be downloaded.