Search code examples
phpincludeob-start

PHP : insert executable php code in HTML


I got simple caching script which is saving php code into HTML. Everything works fine, but I need to add dynamic tracking code into every saved HTML by including a script from another file with include() statement

....

$s_getdata = http_build_query( array(
                   'cat' => 'CAT1',
                   'buffit'=>'TRUE',
                 )
             );
$s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
ob_start();
echo $s_page;
file_put_contents('./index.html', ob_get_contents());
ob_end_clean();

I tried to add this code before ob_start, but it just add code as simple text in string (not working) :

$s_page .= '<?php include("./tr/in.php"); ?>';

Any idea how to do it ? Thanks!


Solution

  • You can do this by 2 ways,

    Option 1: return value as a function from the in.php file,

    your in.php file code,

    function dynatrack() {
       // your dynamic tracking code generation here
       return $code; // where $code is your dynamic tracking code
    }
    

    Your original file,

    $s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
    include("./tr/in.php");
    $s_page .= dynatrack();
    

    Option 2: Get the contents of the in.php file by using file_get_contents again,

    $s_page = file_get_contents('http://example.com/buffer.php?'.$s_getdata);
    $s_page .= file_get_contents('./tr/in.php');
    

    I hope this helps!