简体   繁体   中英

PHP strpos and substr functions causes 'Allowed memory size exhausted' error

The part of my code is the following:

while( $pos1 = stripos( $description, '<style' ) ) {
  $pos2 = stripos( $description, '</style>' ) + 8;
  $description = substr( $description, 0, $pos1 ).
                 substr( $description, $pos2 );     //   <= This string causing the error
}

Sometimes (not all the time!) I receiving the error:

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 107663188 bytes) in /path/to/my/script.php on line 88

88'th line indicated by the '<=' arrow above.

The size of $description variable is about 100 kB's. Besides I don't see any reason to believe that this code can cause accumulation of memory allocation without to be released.

Do you see any flaws in my code?

This code causes memory error

$description = 'hello<style></style>hello<style>';
while( $pos1 = stripos( $description, '<style' ) ) {
    $pos2 = stripos( $description, '</style>' ) + 8;
    $description = substr( $description, 0, $pos1 ).
        substr( $description, $pos2 );     //   <= This string causing the error
}

Looks like the problem caused by the fact that if </stile> is not find - the $description variable will grow up to infinity. This can appear if the <script> tag used in form <script ... /> Now the code is the following:

while( $pos1 = stripos( $description, '<style' ) ) {
  $pos2 = stripos( $description, '</style' ) + 8;
  if( $pos2 < $pos1 ) $pos2 = strpos( $description, '/>' ) + 2;
  if( $pos2 < $pos1 ) break 2;
  $description = substr( $description, 0, $pos1 ).
                 substr( $description, $pos2 );
}

Looks like there are no errors anymore...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM