Search code examples
phpcachingbuffereval

PHP catch eval output


I wanna catch the output of the eval execution and see only the output of $B , any solution for that?

If i execute the code like this i get output twice:

first from eval

second from $B

pls i dont need questions why i am using eval, and that eval is evil.

I need a solution for exactly this example.

<?php
  $A = '<?php echo "Output"; ?>';
  eval(" ?> $A <?php ");
  $B = ob_get_contents();
  echo $B;
?>

Solution

  • You didn't show it so you need to start buffering with ob_start. Then get and clean the buffer so that the buffer will be empty at the end of execution ob_get_clean:

    <?php
      ob_start();
      $A = '<?php echo "Output"; ?>';
      eval(" ?> $A <?php ");
      $B = ob_get_clean();
      echo $B;
    ?>
    

    Alternately you could use ob_clean or ob_end_clean somewhere after the ob_get_contents.