Search code examples
phpdatewhile-loopinfinite-loopstrtotime

Infinite loop on while PHP


First of all, im not a programmer (just have some knowledge of PHP). I made a website with event listing with a select field filtering per month events with Ajax loading.

The code worked perfect for about 3 months. But sudenly 5 days ago, it stoped working and start generating an infinite loop.

I debugged the code and found that a "while" loop is the problem. I'm trying to understand why this worked perfect for some time, and then it just won't. (crashing the server with an infinite loop).

This function just gives the first day of next month. It's working fine.

function first_day_next_month($month, $year){

  $month = str_replace("0", "", $month);

  if ($month == 12){
    return ($year+1)."0101";
  }else{
    return $year.str_pad($month+1, 2, "0", STR_PAD_LEFT )."01";
  }

}

This one, generates the "options" for the select field:

function ddown(){

  $start = strtotime("10 December 2017");

  $end = strtotime("+3 months");

  $current = $start;

  $meses = array(

    "Jan" => "enero",
    "Feb" => "febrero",
    "Mar" => "marzo",
    "Apr" => "abril",
    "May" => "mayo",
    "Jun" => "junio",
    "Jul" => "julio",
    "Aug" => "agosto",
    "Sep" => "septiembre",
    "Oct" => "octubre",
    "Nov" => "noviembre",
    "Dec" => "diciembre"

    );
  $o = "";

  $selected = "";
  $cls = " class=\"gray-out\"";
  while ($current < $end){

    if(date("m", $current) == date("m", strtotime("today")) AND date("Y", $current) == date("Y", strtotime("today"))){
      $selected = " selected=\"selected\"";
      $cls = "";
    }else{
      $selected = "";
    }



    $current = strtotime(first_day_next_month( date("m", $current), date("Y", $current) ));
  }

  return $o;

}

I found out that this piece of the code is generating the infinte loop now:

while ($current < $end){

    if(date("m", $current) == date("m", strtotime("today")) AND date("Y", $current) == date("Y", strtotime("today"))){
      $selected = " selected=\"selected\"";
      $cls = "";
    }else{
      $selected = "";
    }



    $current = strtotime(first_day_next_month( date("m", $current), date("Y", $current) ));
  }

The $current variable is not updating on the while. AS far as I understand this should take the 10 december 2017 to today+3 months and output and "option" for every month between those dates.

Any advice on how to solve this?.

(sorry for my english).

Thanks!


Solution

  • In your first_day_next_month function you have:

    $month = str_replace("0", "", $month);
    

    This is going to replace 10 with 1 which will revert every October back to January.