Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

5 Easy Ways to Syntax Highlight PHP Code

A great to way to share your PHP code with visitors is to display it directly in the browser with automatically generated syntax highlighting. Here is a screenshot showing an example of syntax-highlighted PHP code:

[ Screenshot: PHP code snippet in syntax-highlighted form ]

Displaying your PHP scripts in syntax-highlighted form is an excellent way to share source code details directly with your readers. Rather than zipping the script and requiring users to download, unzip, and open the file in an editor, displaying your code directly saves you and your visitors time, effort, and hassle. Plus, in my opinion, looking at syntax-highlighted PHP code is a beautiful sight, day or night ;)

In this article, we will explore 5 different ways to display the syntax-highlighted source of your PHP scripts. Three of the methods are designed to highlight entire files, and the other two are aimed directly at highlighting individual strings of PHP code. All of these methods employ PHP’s built-in syntax highlighter. Note that all of the code examples and files for this tutorial are available for free download at the end of the article.

The PHP Functions

All of the syntax-highlighting methods presented in this tutorial rely on one of two core PHP functions, highlight_file() and highlight_string():

  • highlight_file() — displays source code for a PHP file
  • highlight_string() — displays source code for a string of PHP code

Each of these functions highlights the target PHP code according to a predefined set of colors, applied via inline CSS applied via <font> elements. The function highlight_file() uses the name of the target file as the parameter and returns the file contents in syntax-highlighted form. Similarly, highlight_string() uses a specific string of code as the parameter and returns it with syntax highlighting applied.

One last note before we dig into the various techniques: use caution and a dash of common sense when it comes to displaying the source of your PHP scripts. Make sure that you are not unintentionally revealing sensitive data such as passwords, salts/hash, user logins, database credentials, and so forth. With that in mind, let’s get on with it..

PHP Syntax Highlighting for Individual Files

Using the PHP function highlight_file(), we can generate “a syntax-highlighted version of the given PHP [file] using the colors defined in the built-in syntax highlighter for PHP.1

Syntax-highlighting via .phps extension

This method is dead-easy if enabled on your server. Simply change the file extension from .php to .phps. Be careful not to reveal the source of any secure data, such as passwords, etc. If syntax highlighting doesn’t seem to be working with this method, try adding the following directive to your domain’s httpd.conf or to your site’s root (or other target directory) htaccess file:

AddType application/x-httpd-php-source .phps

PHP syntax-highlighting via FILE constant

Another easy method for highlighting the syntax of a PHP file is to call the highlight_file() function at the beginning of the file. The first line displayed via the preceding link is the only code needed to highlight any PHP document. Simply add the following code to the target file and open in a browser to see the syntax-highlighted source:

<?php highlight_file( __FILE__ ); ?>

HTML-valid syntax-highlighting for PHP files & strings

This method is nice because it requires no tampering with the target file, and also generates valid XHTML markup for the highlighted source code. To use this method, begin by placing the following code into a blank .php file and name it something like “highlighter.php”:

<?php 

function string_syntax_xhtml( $string, $return = false ) {
	$highlight = highlight_string( $string, true );
	$replace   = str_replace(
		array( '<font color="', '</font>' ),
		array( '<span style="color: ', '</span>' ),
		$highlight 
	);
	if( $return ) {
		return $replace;
	}
	echo $replace;
	return true;
}

function file_syntax_xhtml( $path, $return = false ) {
	return string_syntax_xhtml( file_get_contents( $path ), $return );
}

echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><title></title></head><body>';
string_syntax_xhtml( file_get_contents( 'file_example.php' ) );
echo '</body></html>';

?>

To use this script, edit the “file_example.php” in the penultimate line to reflect the location of your target file. Then, to display the syntax-highlighted source-code of the target file, create a link to the file containing the script (i.e., highlighter.php). That’s all there is to it. Whenever a user clicks on the link to the highlighter.php file, the source code of the target PHP file will be displayed in the browser.

PHP Syntax Highlighting for Individual Strings

Using the PHP function highlight_string(), we can generate “a syntax-highlighted version of the given PHP [string] using the colors defined in the built-in syntax highlighter for PHP.2

Default syntax-highlighting for any PHP string

For on-the-fly syntactical highlighting of PHP strings, we can use PHP’s native function highlight_string(). Using this function couldn’t be easier, simply use this code:

<?php highlight_string('<?php phpinfo(); ?>'); ?>

..and replace the example argument (“<?php phpinfo(); ?>”) with the PHP string of your choice. When the script is processed it will apply syntax highlighting to the input string similar to the following HTML source code for this example (note that the opening and closing <?php and ?> are required with the input string):

<font color="#000000">
   <font color="#007700"><?</font>
   <font color="#0000bb">php phpinfo</font>
   <font color="#007700">(); </font>
   <font color="#0000bb">?></font>
</font>

String syntax-highlighting with automatic quote-escaping

Generating highlighted code from strings of PHP code using highlight_string requires us to escape quotes (e.g., ' , " ). Depending on your input string, escaping e\v\e\r\y quote may prove tedious and boring, opening wide the doors to potential error. Fortunately, the following technique eliminates the frustration by cleaning things up automagically:

<?php code(); ?>
          $string = '[ place your "highly quoted" PHP string here ]';
<?php code(); ?>

<?
function code() {
          static $on = false;
          if ( !$on ) {
               ob_start();
          } else {
               $buffer = "<?\n" . ob_get_contents() . "?>";
               ob_end_clean();
               highlight_string( $buffer );
          }
          $on = !$on;
}
?>

To use this script, place your target string between the “<?php code(); ?>” declarations and paste into any PHP file. Calling this file will then generate the syntax-highlighted source of the entire code string. Special thanks to phella.net for sharing this technique in the php.net forums2.

Download the demo pack

Well, that does it for this article! I have also put together a demo pack containing all of the files and code for this tutorial. To use the demo, download the following zip file and upload its unzipped contents to any PHP-enabled server (i.e., PHP required).

Footnotes

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
Wizard’s SQL for WordPress: Over 300+ recipes! Check the Demo »

4 responses to “5 Easy Ways to Syntax Highlight PHP Code”

  1. bryan nina manalang macaspac 2009/09/09 5:37 pm

    THANKS FOR THE INFORMATION THAT YOU SHARE IVE LEARN SO MUCH IN GUYS KEEP UP THE GOOD WORK!!

  2. Thanks for this. :) Used one of your example today when I noticed that the place where I have my blog didnt allow .phps or highlight_* functions. :) But the “(X)HTML-validating syntax-highlighting for PHP files and strings” example did work fine. Created a /source-code/index.php?the-file-to-show.phps site with it. (Added some security checks ofc so that only files I want to be included can be included.) :) Cheers mate!

  3. Jeff Starr 2010/07/04 1:47 pm

    Sweet! Thanks for the feedback! :)

  4. thanks a lot . . .was looking for a code tp print my php code as it is in the browser and highlight_file( ) does the job

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
.htaccess made easy: Improve site performance and security.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.