nyumerics
nyumerics

Reputation: 6547

Read PHP files using PHP?

I have a PHP file. I want to read the PHP code written inside that file. The script I am executing is in the file 'test.php'.

<?php
$test = file_get_contents('test.php');
echo '<pre>'.$test.'</pre>';
?>

The output in browser window is:

'.$test.'

'; ?>

another test on the file:

<!DOCTYPE html>
<html>
<head>
  <title>Canvas Home</title>

  <link rel="shortcut icon" href="http://localhost/collaborate/icons/collaborate.ico">
<?php
    echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheets/".basename(__FILE__,'.php').".css\">";
    echo "<script type=\"text/javascript\" src=\"js/".basename(__FILE__,'.php').".js\"></script>";
?>
  <link rel="stylesheet" type="text/css" href="stylesheets/navs.css">
</head>

<body>
  <div></div>
</body>

</html>

gave the output:

"; echo ""; ?> 

Can someone explain me what is happening in the first file? I expected the returned string to be simply echoed.

Also in the second file, the first simple HTML part is echoed and hence gets interpreted as HTML, understood. But what happens then? Why is the echo command itself displayed?

I basically want to achieve reading the source of any script file rather than it being executed, i want it displayed in the browser window.

Upvotes: 0

Views: 339

Answers (2)

thibauts
thibauts

Reputation: 1648

Your browser is trying to interpret the file as HTML code, as has been pointed out by Mark B. A clean solution would be to make the browser interpret the response body as plain text, like this :

<?php
header('Content-Type: text/plain');
echo file_get_contents(__FILE__);
exit;

Note: In PHP __FILE__ always refers to the current file.

Upvotes: 0

Marc B
Marc B

Reputation: 360572

Since you're outputting the raw PHP code to the browser, the browser is trying to render <?php as an HTML tag. You'll probably want to run the code through htmlspecial chars so any HTML metacharacters in the PHP code are sent encoded, and then NOT rendered by the browser. e.g.

$code = file_get_contents('script.php');
echo '<pre>', htmlspecialchars($code), '</pre>';

And note that your browser LIES to you about output, especially when you're working with PHP and/or HTML. Remember that the browser's job is to RENDER html, and anything that LOOKS like HTML, including PHP tags. If you get wonky looking output in the browser, ALWAYS do a "view source" to see the raw 'code' of the page - you'll probably see your PHP and html code there, coming through just fine.

Upvotes: 4

Related Questions