Why would this PHP be causing an execution timeout?

I’ve just released the first version of a WordPress plugin I wrote, and I’ve received a report that at least one of the people using my plugin is receiving an execution timeout error citing this block of code:

function getNumericAttributeFromHTML($htmlElement, $attribute){
    $attrStartPos = stripos($htmlElement, $attribute) + strlen($attribute);

    $strOffset = 0;
    $searchWithin = substr($htmlElement, $attrStartPos);

    while(!(is_numeric($searchWithin[$strOffset]))){
        $strOffset++;
    }
    $attrStartPos += $strOffset;

    $strOffset = 0;
    $searchWithin = substr($htmlElement, $attrStartPos);

    while((is_numeric($searchWithin[$strOffset]))){
        $strOffset++;
    }

    return substr($htmlElement, $attrStartPos, $strOffset);
}

This function is called twice per image on the page. Am I being crazy inefficient, or is it possible their host is just terrible?

Read More

Thanks in advance for any help you can provide.

Related posts

Leave a Reply

3 comments

  1. while(!(is_numeric($searchWithin[$strOffset]))) will run infinte times if $searchWithin has no numeric character!

    Note the problem might be somewhere else.

    To pinpoint the actual problem I suggest you get the reproducible steps from the bug and use a profiler to profile the code. You’ll surely find where the problem is.

  2. You have an infinite while loop. You’re just incrementing the value of $strOffset without changing the value of $searchWithin[$strOffset] so if it’s not numeric, it never will be and will get stuck looping forever.

  3. If its causing timeout, well you have a extra large or infinite loop. You have 2 loops here, check if they are infinite.

    If this is not the problem, increase the maximum execution time by adding this at start of your script:

    ini_set('max_execution_time', 36000); //3600 seconds = 1 hour