Infinite loop with data stream in PHP

Asked

Viewed 160 times

1

I have the following code below:

<?php
$Start = microtime(true);

$Code = <<<'Code'
<?php
for($i = 0; $i < 300; $i++){
    echo '.';
}
Code;

include 'data://text/plain,'.$Code;

echo microtime(true) - $Start;

PHP is entering an infinite loop that was not meant to enter. It seems that the stream cannot store the value of the variable $i. How to solve this problem?

  • the allow_url_include directive is enabled?

  • yes, it is activated...

  • Curious. I had never seen this type of code, but when performing the tests I understood why of the infinite loop. $i can never be increased because it seems that its scope does not exist. Use echo $i and set the maximum running time to 5 seconds to check.

  • Only 0.. variable appears $i is not being written...

1 answer

2


By the tests the problem is in the character +

It is deleted in the final code because it is not correctly escaped.

A code that works here in your case is this:

$Start = microtime(true);

ini_set('max_execution_time', 5);

$Code = <<<'Code'
<?php
    for($i=0; $i < 300; $i++) { 
    echo $i . "\n";
};
?>
Code;


include_once 'data://text/plain,' . urlencode($Code);

echo microtime(true) - $Start;
?>

And here using what you mentioned about php://memory

<?php
$Start = microtime(true);

ini_set('max_execution_time', 5);
$Code = <<<'Code'
<?php
    for($i=0; $i < 300; $i++) { 
    echo $i . "\n";
};
?>
Code;

 $fp = fopen('php://memory', 'rw'); 

fwrite($fp, urlencode($Code)); // escapando corretamente os caracteres 

fseek($fp, 0); // Retornando o ponteiro ao inicio do bloco de memória
include_once 'data://text/plain,' . stream_get_contents($fp); // incluindo como um arquivo

echo microtime(true) - $Start;
?>
  • And I don’t want the code outside Heredoc. I want the code inside Heredoc. I’m trying to find a way to execute the same code, but with the stream php://memory and find out why this problem occurred.

  • By my tests, the problem is in the $i++ loop. It is not like this in the final text and $i is never incremented. With Val I got a result that I think will work for your case.

  • Read my answer..

  • That’s weird. How that code worked?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.