php读取其他php文件

I have one php page (index.php) with following contents:

<php
    include("{$_SERVER['DOCUMENT_ROOT']}/somefunction.php")
    echo "hello world";
?>

Now I want to read the contents of index.php via another php-file (test.php) The result I want to get is:

line 1: include("{$_SERVER['DOCUMENT_ROOT']}/somefunction.php")
line 2: echo "hello world";

This is what I already tried, but it won't work:

$phppage="{$_SERVER['DOCUMENT_ROOT']}/index.php";
$handle = fopen($phppage, "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        echo $line;
    }
    fclose($handle);
}
else {
    // error opening the file.
    echo "An error occured";
}

It just echoes an empty string.

Problem solved :-)

Actually your code is working. The problem is it will not displayed on browser . Since it contain html special character like <

So either print The result with in a <pre> </pre> tag.

or use htmlentities()

echo htmlentities($line);

or remove <?php ?> from the file index.php

If you don't need the line numbers, which are not made by your code, you could do:

readfile('index.php');

or

echo file_get_contents('index.php');

Which will work as long as you work in the same directory. If you need line numbers:

$lines = explode("
",file_get_contents('index.php'));

foreach ($lines as $key => $line) echo "line {$key+1}: $line
";

And if you don't want to echo, well, that's obvious.

When you say "it won't work" - do you get any error messages? Have you tried switching on error_reporting and display errors?

This is possibly security related - no permission to open the file.

Try using a relative path and double check that there are no basedir restrictions in place.

Are you looking for this...

show_source()

This function shows your PHP code in the browser..

URL: http://www.w3schools.com/php/func_misc_show_source.asp

this is working try this 

read.php as 

<?php
$phppage=realpath("index.php");
$data = htmlentities(file_get_contents($phppage));
echo $data;

?>

index.php as

<?php

$absolute_path = realpath("somefunction.php");
include($absolute_path);
echo "hello world";
?>