<?php

    // dest must be set to null to insure that the loop will continue until an actual valid
    // comic date is found.
  $dest = '';

    // this count is a performance precaution that will probably never come up
  $count = 0;

    // this loop finds a valid comic.
  do
  {
      // the performance precaution continues
    $count++;

      // Randomly generate numbers for day, month, and year. Year is set to never go beyond the
      // current year by virtue of 2024 tag. Change 2002 to whatever year your comic
      // started.
    $rDay = rand(1, 31);
    $rMonth = rand(1, 12);
    $rYear = rand(2000, 2024);

      // Make certain rDay is properly formatted
    if (strlen($rDay) < 2)
    {
      $rDay = '0'.$rDay;
    }

      // Make certain rMonth is properly formatted
    if (strlen($rMonth) < 2)
    {
      $rMonth = '0'.$rMonth;
    }

      // Combine the strings for the file_exists() function. Change .html if your archives have
      // a different file extension.
    $rFile = 'd/' . $rYear . $rMonth . $rDay . '.html';

      // The highest count ever got in tests was 6. If count reaches a number as high as 1000,
      // something simply must be wrong. to prevent whatever is wrong from resulting in an
      // endless loop, this will set the destination to the newest comic.
    if (count > 1000){$dest = '/d/20240228.html';}

      // Check to see if the file exists and set dest to end the loop if it does. The / is added at
      // this point as opposed to before because having it already on the string while checking for
      // the file with file_exists() seemed to keep it from working in another file of mine.
    if (file_exists($rFile)){$dest = '/'.$rFile;}
    
  } while ($dest == '');

    // This opens up the page with the comic.
  header('Location: '.$dest);

?>
