Highlight Source Code in Your PHP Application

If you run a Website about programming, chances are that you display source code on your site’s pages. Wouldn’t it be great if the source code was highlighted — displayed using different colors — in the same way the desktop programming editors and IDEs display it? This would certainly make it much easier for your visitors to read the code.

This tutorial explains how you can highlight source code shown on your Website for a number of programming languages without manually formatting and hand-coding the display.

I’ll show how to highlight source code in two ways:

  1. Using the PHP’s built-in highlighter for PHP source code
  2. Using PEAR’s Text_Highlighter package to highlight the source code for virtually any programming or markup language

This tutorial forms a sequel to my previous article, titled Use BB Code in Your PHP Application, and it uses the same setup for the code environment. While this article doesn’t assume you’ve read the previous one, you might want to take a look at the Setup section of it.

Using PHP’s Built-in Source Highlighter

PHP offer two functions for highlighting PHP code: highlight_file() and highlight_string(). Both functions return the same results, but each has its own specific input parameters. As their names suggest, the first function takes the filename of the PHP script whose code is to be highlighted, while the second takes the input as a string.

A Quick Example

Let’s take a look at an example of the highlight_string() function in action:

<?php  include_once 'init.inc.php'; 

if (!empty($_POST['text'])){ 

echo '<div style="border: solid 1px orange; padding: 20px; margin: 20px">';      highlight_string($_POST['text']);      echo '</div>';  }  ?> 

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">      <textarea name="text" style="width: 300px; height: 200px"><?php           echo @$_POST['text'];       ?></textarea>      <br />      <input type="submit" />  </form>

This script displays a simple textbox into which you can type or paste the PHP code you want to highlight. The code for the example is available in this article’s code archive and a live demo is available online. The purpose of the init.inc.php file required at the beginning of the script was explained in the Setup section of my previous article.

Here’s a screenshot of the script in action.

Highlight Source Code in Your PHP Application

As you can see, the highlighted version of the code is much clearer and easier to follow than the standard black-and-white code.

Color Customization

The PHP highlighter uses the following colors to display the code:

Highlight Source Code in Your PHP Application

The identifiers in the first column are actually the names of PHP configuration directives. This means that you can customize the highlight colors by altering the PHP configuration. So, if you want your keywords to be pink for a change (not pretty, I know, but this is just an example), you can do so by using a simple .htaccess file, containing:

php_value highlight.keyword #ff00ff

Drawbacks of the Native PHP Method

As you can see, this method of highlighting PHP source code is very easy to use, gives great results, and is customizable. However, it has some downsides:

  • It will work properly on PHP source code only. Sometimes you can get somewhat acceptable results when highlighting other programming code, like HTML or JavaScript, but most times, the results won’t be very good. This is simply because these highlight functions were designed specifically for PHP code.
  • The resulting HTML code, after the highlighting is performed, is not XHTML-compliant. This issue is corrected in PHP5, but in PHP4, the highlighter uses the <font> tag, something that is considered almost a crime by today’s Web coders.

Using PEAR: Say Hello to the Text_Highlighter Package

In its repository of PHP libraries, PEAR has a special package for highlighting source code. It’s called Text_Highlighter, and its details, documentation and downloads are available online.

This package features:

  • The ability to highlight the source code for 12 different programming languages
  • Extensiblility; the package allows you to define more languages using a simple XML file
  • Line numbering and tab size options are available
  • The ability to highlight code in the console window
  • Output is provided in XHTML format, using <span> tags for semantics and CSS styles for formatting

A Few Words on the Setup

To prepare your system to run the following examples:

  1. Install the PEAR core libraries
  2. Install the Text_Highlighter package

    Set up your environment, a.k.a. copy my 10-line init.inc.php file

These steps were described in detail in the previous article and are not hard to do. Don’t be scared of the word "install" here: it’s basically just a "copy" operation. The setup doesn’t require you to have any special privileges on the server, and is easily done in low-cost shared hosting environments. If you want to see the directory structure of an example setup, browse the code examples from this article.

Usage

Once you’ve finished the setup, you can start using the highlighter. In order to highlight the PHP source code contained in, let’s say, $some_source_code variable, all you need to do is:

  1. Include the class definition:
    require_once 'Text/Highlighter.php';
  2. Create an object of the class:
    $highlighter =& Text_Highlighter::factory('php');
  3. Call the highlighting method and print the output:
    echo $highlighter->highlight($some_source_code);

Test the Highlighter

Here’s a simple script that you can use to test the highlighter package:

<?php  include_once 'init.inc.php'; 

if (!empty($_POST['text'])){ 

echo '<link rel="stylesheet" href="hilight.css" />';      echo '<div style="border: solid 1px orange; padding: 20px; margin: 20px">'; 

require_once 'Text/Highlighter.php';      $highlighter =& Text_Highlighter::factory('php');      echo $highlighter->highlight($_POST['text']); 

echo '</div>';  }  ?> 

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">      <textarea name="text" style="width: 300px; height: 200px"><?php echo @$_POST['text']; ?></textarea>      <br />      <input type="submit" />  </form>

Here’s a screenshot of the script in action.

Highlight Source Code in Your PHP Application

You can play around with a live demo here.

Colors of the Rainbow

As you can see, the PEAR highlighter is working a lot like the built-in PHP highlighter we looked at first. The only visible difference from the previous example is in the number of colors: there are seven here, rather than the three we saw in the first example. This is made possible because the PEAR highlighter is more granular when it comes to the "ingredients" of the source code.

If you view the source of the result of the script above, you’ll see that the highlighting places <span class="hl-something"> tags around the different source code elements. The CSS class names, such as hl-xxxx, need to be defined in order for the coloring to be displayed.

You can take a peek at the CSS file used in the example above if you wish. As you can see, 18 style definitions are used in the CSS file, 15 of which are related to the different elements you might find in a source code file: variables, strings, brackets, quotes, etc. The CSS definitions give you the power to customize the colors used for highlighting as you find appropriate.

It’s Not All PHP!

So far, all the examples have focused on coloring PHP code. But what if your site isn’t about PHP? Tough luck, some might think, but not the Text_Highlighter package, which offers a colorful hand to 11 other programming and markup languages, including C++, CSS, JavaScript, XML (also used for HTML files), to name a few.

To highlight the code of another language, just change the ‘php’ in the below line to reflect the language of your choice:

$highlighter =& Text_Highlighter::factory('php');

Want to highlight CSS?

$highlighter =& Text_Highlighter::factory('css');

You can now highlight a CSS stylesheet.

Here’s a full list of the language identifiers you can use when creating the highlighter object:

  • 'cpp'
  • 'css'
  • 'diff'
  • 'dtd'
  • 'javascript'
  • 'mysql'
  • 'perl'
  • 'php'
  • 'python'
  • 'ruby'
  • 'sql'
  • 'xml'

You can use this live demo to see how other languages are colored. The source file is available in this article’s code archive.

As a side note: you’ve probably noticed already that an object of the highlighter class is created using its factory() method. This is a popular object-oriented technique (an OO pattern). Although an understanding the inner workings of the factory pattern is not required for this article, you can still find out more if you’re interested; this PHPPatterns entry is a good starting point.

Fine Tuning the Highlighter

In addition to coloring, the highlighter can:

  • Display line numbers along with the source code
  • Use different tab sizes to indent code

The first feature can be activated in two ways: using a numbered list (<ol>) or an HTML table. In the latter case, you can use CSS to define a style for the column that contains the numbers, which is different than the one containing the source code.

These options are passed as an array with keys:

  • 'numbers': This setting accepts the following values:

    • 0: the default value, meaning no numbering is used
    • HL_NUMBERS_LI: an ordered listing will be used
    • HL_NUMBERS_TABLE: the code will be displayed in a table
  • 'tabsize': This option takes an integer value. It sets how many &nbsp; will be used to replace a tab.

If you choose the table option, you can use the following CSS selectors to customize the look of the table:

  • h1-main – for the row with the source code
  • hl-gutter – the numbering row
  • hl-table – the whole table

Take a look at this article’s stylesheet for an example. The three CSS selectors mentioned above can be found at the bottom of the stylesheet.

A sample options array will look like this:

    $options = array(              'numbers' => HL_NUMBERS_TABLE,              'tabsize' => 4,          );

Setting the Options

There are two ways to set the options for highlighting:

  1. The easy way: just add the options to the factory method. This is the simpler method in terms of syntax, but it exists only for backwards-compatibility purposes.
    $highlighter =& Text_Highlighter::factory('php', $options);
  2. The proper way: use the renderer object.

As mentioned above, in addition to the browser, the highlighter can also color code in the console window. In the future new display devices, like PDAs, phones, your beloved iPod or (last, but not least) your kitchen sink may also be supported — who knows? To allow for this type of forward-compatibility, the display part of the work is passed to renderer objects. So far, two renderers exist: HTML and Console. All you need to do is create a renderer object, then pass it to the highlighter. Here’s how:

    require_once 'Text/Highlighter.php';      require_once 'Text/Highlighter/Renderer/Html.php'; 

$options = array(              'numbers' => HL_NUMBERS_TABLE,              'tabsize' => 4,          ); 

$renderer =& new Text_Highlighter_Renderer_HTML($options);      $highlighter =& Text_Highlighter::factory('php');      $highlighter->setRenderer($renderer);      echo $highlighter->highlight($_POST['text']);

The full source code listing is available in this article’s code archive. A live demo using the HTML renderer and tables to display the source code is also available. Here’s a screenshot of the script in action.

Highlight Source Code in Your PHP Application

Other Options

Here are some other options you might want to take a look at that are not covered in this article.

  • GeSHi: Generic Syntax Highlighter – a non-PEAR highlighter package, currently supporting 35 programming languages.
  • Aidan Lister’s PHP repository contains two classes that use and extend the native PHP coloring. The first class adds line numbers and makes the PHP functions into links to the PHP manual. The second does the same, but in its own way, without the use of the native PHP functions. It also produces XHTML output and can optionally use a stylesheet for color definitions.
  • Enscript is a command line tool for syntax highlighting. An example use of it is this WordPress plugin.

Summary

In this article, we discussed in detail two ways to highlight source code in your PHP application. If you want to quickly colorize come PHP code, make a call or two to the native highlighting functions that are built into the language. Or, if you want to highlight more languages and have more display options, consider installing a copy of the PEAR’s Text_Highlighter package.

You now have a basic knowledge of how to use color coding to enhance the readability of Web pages that contain source code, and improve your visitors’ experience.

Replay

Category: programming Time: 2005-04-11 Views: 1
Tags:

Related post

  • Use BB Code in Your PHP Application 2005-02-22

    Many Websites allow visitors or administrators to contribute to the sites's content through various means: a Content Management System, forums, blogs, or other commenting systems. When you're building such sites, it's a good idea to provide users wit

  • Show jQuery Source Code In Your WordPress Blog 2010-11-17

    Want to include jQuery source code in your WordPress blog without editing through lines and lines of formatting to show source code snippets? Example: How to setup 1. Install the WordPress plugin called SyntaxHighlighter Evolved. 2. Enter the code in

  • Is Your PHP Application Affected by the Y2K38 Bug? 2010-08-24

    I don't want to be too alarmist, but try running the following PHP code on your system: <?php $date = '2040-02-01'; $format = 'l d F Y H:i'; $mydate1 = strtotime($date); echo '<p>', date($format, $mydate1), '</p>'; ?> With luck, you'll s

  • How to prevent source code theft in web application development 2016-06-25

    I'm developing a webapplication working with PHP, SQL DB and other technologies. I'm always considering someone stealing the source code or using it to other means. How can you prevent someone from stealing your source code? If that happens what is t

  • What are main differences between Source Code Analysis vs Static Application Security Testing(SAST)? 2014-08-12

    Do these 2 terminologies refer to the same thing? https://www.owasp.org/index.php/Source_Code_Analysis_Tools http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#.NET Some of the tools overlap. Makes you wonder. If they are different c

  • What happens with the source code when submitting an application 2011-10-18

    This is a follow up question for: How updates are handled for commercial applications? When I submit an application for inclusion in the Software Center, I have to upload a Debian source package. What happens with the source code? Does it get publish

  • Where do you find the source code of keyboard shortcut application? 2013-11-15

    Where do you find the source code of application that allows you to customize the keyboard shortcut that is built into ubuntu? The application that I am talking about is shown in the image below. --------------Solutions------------- This is not an ex

  • Is it OK to release the source code for your own Xbox Live indie game? 2011-04-17

    Between not being sure how to phrase my question for Google and not being a lawyer, I thought it might be easier to ask you guys. Specifically, I want to know if it's OK to sell an Xbox Live indie game while simultaneously distributing the source cod

  • Preventing mysql deadlocks in your php application that uses SELECT- LOCK IN SHARE MODE 2011-10-18

    If I understand SELECT ... LOCK IN SHARE MODE correctly, you can place it into a mysql transaction to select the rows you will be working with during that transaction. This is done in order to "lock out" those selected rows from other session's

  • Highlighted source code inline with Latex/Minted? 2013-10-07

    I am using the minted package (based on pygments) to do syntax-highlighting for xml-code in my Latex documents. However I did not find an option to make it display the code inline. \mint{xml}|<?xml version="1.0" ?>| does a single line but

  • Should we protect web application source code from being stolen by web hosts through obfuscation? 2013-08-05

    Is it worth to obfuscate a java web app source code so that the web host cannot make wrong use of the code or even steal your business? If so, how should this be dealt with? How should we obfuscate? We are a new start up launching a product in market

  • PHP source code was shown on the webpage - security issue ? 2014-01-21

    Hi Till, I am not sure this is my setting problem, I am using ISPConfig version 2.2.24 1) I have enable php globally and uncheck the PHP Scripts and PHP Safe Mode options in one of my virtual site, say www.example.com 2) There is a test.php program i

  • Should You Close Your PHP Code Tags? 2010-09-18

    Even those with a modest grasp of PHP know that code must be enclosed within special <?php and ?> tags. note: Alternative PHP tags You may also be aware that PHP code can be delimited with the lesser-used <script language="php"> and

  • Is it possible for Apache to display PHP source code if PHP crashes? 2012-11-23

    This is more of a security question: Are there any circumstances (i.e. running PHP as a CGI binary versus Apache module, examples of poor default configurations, etc.) where Apache would render the unprocessed source code for a PHP script if PHP were

  • How do you put a price on your source code? 2013-08-01

    I was asked to sell the source code (along with existing users) of small utility app I created years ago. I've investigated how to put a price on the source code but so far haven't come up with a good solution. I've searched the net, but haven't foun

  • Source code highlighting 2014-10-22

    I am looking for a text editor (best would be an Eclipse plugin) which lets me highlight source code lines automatically (programatically) according to a set of given line numbers. Say, I have a file src.java and the set { 3, 18, 19, 20, 101, ... } w

  • Will the following PHP code result in source code info leak/disclosure? 2015-05-18

    I'm aware of this vulnerability via PHP's filter stream wrapper that is able to disclose PHP source code: file=php://filter/convert.base64-encode/resource=filename.php. So I went ahead to guard against this kind of attack/exploit, by filtering for/aw

  • Docker - Application source code updates 2016-01-27

    I know by now that the source code of your application should be copied using ADD to live inside of the docker container. This seems like a good idea, but what if I want to be able to update my application source code say - twice a day, or even more

  • Where to place source code for applications compiled from source? 2013-09-20

    In the past when I have compiled applications from source I have extracted the source code to ~/src and compiled from there. I realize now that there may be no need for me to create the ~/src directory, as Linux probably already has an established lo

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.803 (s). 13 q(s)