Friday, May 10, 2013

Render/Highlight PHP code on browser

To render any PHP file [the code itself] on screen we can use highlight_string() function. Check the following example.

<?php
highlight_string("
 <?php
  \$sal = 10000;
  echo 'Hello';
  echo 'Salary is ' . \$sal;
 ?>
");
?>

 

The function takes a string ( PHP code ) as its argument. It uses the in-built syntax highlighter and adds necessary wrapper tags around PHP keywords and then echoes on screen. The above code renders the following output ::



Notice all the special characters need to be escaped. For example if we use
<?php
highlight_string("
<?php
 $sal = 10000;
?>

");
?>

PHP would look for a variable called $sal during variable expansion  which is not defined earlier. Hence it may generate an error.

We can load a whole PHP file and render the whole code on screen with the highlight_file() function. Check the example below.

<?php
highlight_file("index.php");
?>


And here is the output. It is showing the whole code of "index.php" within "htdocs" folder of my Xampp installation. 




An URL can be passed as argument with the highlight_file() function as shown in the below example.

<?php
highlight_file("http://localhost/index.php");
?>


But you can't see the PHP coding in this case as the PHP file in the URL is first executed and then resultant HTML is shown on screen. This is obvious as otherwise server-side codes can be easily exposed to unauthorized users.

To use http URLs with highlight_file() function, "allow_url_include" must be set to "on" in php.ini configuration file.

However, HTMLs and JavaScripts are not highlighted.

No comments: