Home » Php » include – file_get_contents and php code

include – file_get_contents and php code

Posted by: admin July 12, 2020 Leave a comment

Questions:

Hello is there a way to take the content of a php file while processing the php code in it?
I need to include a code into another page but I need to print the content it in a specific position.

If I use include the code will be printed before the html tag of course cause it’s processed before the page, but if I use file_get_contents the content is taken in the page but if I have some php tags I’ll get those too as plain text.

Thank you.

EDIT: sorry guys seems like I was drunk while I was writing. I corrected.

I have an engine that processes the page contents, puts them into a variable and then print them in a specific position within the html page. In the engine I need to “embed” the code of other “static” pages that could have some php tags. If I use file_get_contents I will get the content as plain text (with php tags not parsed) if I use include it just won’t work cause it’s not the function for it. So I what I need is to embed the PROCESSED code into the engine (as ready-to-be-printed HTML).

How to&Answers:

You can use an output buffer to include a PHP file but save the resulting output for later use instead of printing it immediately to the browser.

ob_start();
include('path/to/file.php');
$output = ob_get_contents();
ob_end_clean();

// now do something with $output

Answer:

Your question is not 100% clear, but it looks like you want to include a remote php source, you can use include(“http://domain.com/path/to/php.phps”); instead of a file_get_contents.

You said that you just need a part of the remote code, if it’s that, you can use the file_get_contents, get this portion of the code with substr or reg exp save on a local file and include or do a eval.

None of the solutions are secure nor recommended, you should never include remote files to direct evaluation on your code.

Answer:

If I understand correctly; you are trying to load a php file in to read its contents and execute it at the same time.

ie:
include('/foo/bar')
and
file_get_contents('/foo/bar')

The following function does both and returns the contents of the file assuming it exists.

function load_and_process($path) {
    if(file_exists($path) {
        include($path);
        return file_get_contents($path);
    }
    return false;
}

and call it like so:

if($file_contents = load_and_process('/foo/bar')) {
    echo "Loaded $file_contents from /foo/bar";
}