Include and ob_get_clean not working properly

1.4k views Asked by At

I have three php files: engine.php, links.php and test.php

In theory when I call _insert() function in test.php it should replace a string with the output of links.php, instead ob_start() and ob_get_clean() are ignored, and the output of links.php is just echoed.

engine.php

function db() {
    require("config.php");
    $conn = @mysql_connect($host, $uname, $pass) or die("DB error: ".mysql_error());
    @mysql_select_db($db) or die("DB error: ".mysql_error());
    @mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); #UTF-8 FIX
}

function _include($x) {
    if (preg_match("/<!--Include:(.*)-->/", $x, $matches)){

        ob_start();
        include($matches[1]);
        $output = ob_get_clean();

        return preg_replace("/<!--Include:(.*)-->/", $output, $x);
    }

}

links.php

<?php
$query = @mysql_query("SELECT title, description, url FROM links ORDER BY id") or die("DB error: ".mysql_error());

while($row = @mysql_fetch_array($query)) {
    $url = $row["url"];
    $title = $row["title"]; 
    $description = $row["description"];
    echo "<a href=\"$url\">$title</a>: $description";
}

@mysql_close($conn) or die(mysql_error());
?>

test.php

<?php

require("engine.php");

db();

echo _include("<div><!--Include:links.php--></div>");

?>

Instead of outputting a series of links inside a div, it skips the return completely end echoes from links.php as if there was just an include and no ob_start() and ob_get_clean().

Why?

1

There are 1 answers

1
Cedric On BEST ANSWER

You can return a string from links.php :

<?php
$query = @mysql_query("SELECT title, description, url FROM links ORDER BY id") or die("DB error: ".mysql_error());

$links =''; //

while($row = @mysql_fetch_array($query)) {
    $url = $row["url"];
    $title = $row["title"]; 
    $description = $row["description"];
    $links .= "<a href=\"$url\">$title</a>: $description";//
}

@mysql_close($conn) or die(mysql_error());
return $links;//

then, in engine.php :

function _include($x) {
    if (preg_match("/<!--Include:(.*)-->/", $x, $matches)){

        //ob_start();
        $output = include($matches[1]);
        //$output = ob_get_clean();

        return preg_replace("/<!--Include:(.*)-->/", $output, $x);
    }

}