print

Just my two cents – a function that takes PHP source code from a file and decodes it to text/plain MIME-type.

Cheers,
Joel A. Villarreal Bertoldi

Example:
####################################

samplefile.php:

parser.php:

####################################
Results:
####################################

Array
(
[0] => $a = 1;
[2] =>
[3] => /* This is my file*/
[4] => echo $a;
[5] => ?>
)

####################################
Miki Roro 31-Aug-2009 01:39
highlight_file() wraps HTML tags around PHP constructions,
so it’s not useful for CLI. If you want to have highlighted source
in command line, use this script:

<?php
$php = $argv[1]; // set a path
if(!$php)
$php = $argv[0];

$c_string = ini_get('highligth.string'); // get ini values
$c_comment = ini_get('highlight.comment');
$c_keyword = ini_get('highlight.keyword');
$c_default = ini_get('highlight.default');
$c_html = ini_get('highlight.html');

$source = highlight_file($php, true); // load highlighted source

$source = str_replace('‘, ‘’, $source); // replace html tags
$source = str_replace(‘‘, ‘’, $source);
$source = str_replace(‘‘, ‘’, $source);
$source = str_replace(‘‘, ‘’, $source);
$source = str_replace(‘‘, ‘’, $source);
$source = str_replace(‘‘, ‘’, $source);

$source = str_replace(‘', '', $source); // strip and
$source = str_replace('
', '', $source);
$source = str_replace('
', "\n", $source);
$source = str_replace(' ', ' ', $source); // remove &nbsp and entities
$source = html_entity_decode($source);

echo $source;
?>

Then type `php highlight.php some_other_script.php` to have
colorful source in terminal window. Tested under Ubuntu.
dynamicflurry [at] gmail dot com 04-Aug-2009 12:33
Here's a great function I found to add numbers to your highlighted code:

<?php
function highlight_num($file)
{
$lines = implode(range(1, count(file($file))), '
');
$content = highlight_file($file, true);

echo '

.num {
float: left;
color: gray;
font-size: 13px;
font-family: monospace;
text-align: right;
margin-right: 6pt;
padding-right: 6pt;
border-right: 1px solid gray;}

body {margin: 0px; margin-left: 5px;}
td {vertical-align: top;}
code {white-space: nowrap;}
';

echo "

\n$lines\n \n$content\n

";
}
highlight_num(__FILE__);
?>
afugit at imavex dot com 24-Jul-2009 01:42
This function will not only echo out the code but will add line numbers. The extra code is for the multi-line and single-line comments using /* and */ and making sure they are highlighted appropriately. If not used, the multi-line comments will not be displayed in orange (or the default comment color).

Anthony

=============

<?php
function renderFile($filename) {
if(file_exists($filename) && is_file($filename)) {
$code = highlight_file($filename, true);
$counter = 1;
$arr = explode('
', $code);
echo '

' . "\r\n";
foreach($arr as $line) {
echo '
' . "\r\n";
echo '

' . "\r\n";

// fix multi-line comment bug
if((strstr($line, '/*') !== false) && (strstr($line, '*/') !== false)) { // single line comment using /* */
$comments = false;
$startcolor = "orange";
}
elseif(strstr($line, '/*') !== false) { // multi line comment using /* */
$startcolor = "orange";
$comments = true;
}
else { // no comment marks found
$startcolor = "green";
if($comments) { // continuation of multi line comment
if(strstr($line, '*/') !== false) {
$comments = false;
$startcolor = "orange";
}
else {
$comments = true;
}
}
else { // normal line
$comments = false;
$startcolor = "green";
}
}
// end fix multi-line comment bug

if($comments)
echo '

' . "\r\n";
else
echo '

' . "\r\n";

echo '

' . "\r\n";
$counter++;
}
echo '

' . $counter . ': ' . $line . ' ' . $line . '

' . "\r\n";
}
else {
echo "

The file $filename could not be opened.

\r\n";
return;
}
}
?>
nospam at mbeulens dot nl 11-Jul-2009 05:00
This is my try on linenumbers
<?php
public static function highlight_file_with_line_numbers($file) {
//Strip code and first span
$code = substr(highlight_file($file, true), 36, -15);
//Split lines
$lines = explode('
', $code);
//Count
$lineCount = count($lines);
//Calc pad length
$padLength = strlen($lineCount);

//Re-Print the code and span again
echo "";

//Loop lines
foreach($lines as $i => $line) {
//Create line number
$lineNumber = str_pad($i + 1, $padLength, '0', STR_PAD_LEFT);
//Print line
echo sprintf('
%s | %s', $lineNumber, $line);
}

//Close span
echo "
";
}

?>
Anonymous 10-Apr-2009 08:02
I get linenumbers this way... cause I don't like tables :p

<?php

function highlight_linenumbers ($page)
{

// remove and global
$code = highlight_file($page, true) ,36,-15);

echo '

    ';

    $arr = explode('
    ', $code);
    foreach( $arr as $line )
    {
    // removing newline
    $line = substr($line, 0, -1);

    //empty lines
    if( preg_match('`^( )*$`',$line) ) $line = ' ';

    // add colour from the previous line
    if( !empty($last_colour) ) $s = ''. $s;

    // Supposing we open more spans on a line than closing... let's do this properly
    // We have at most one currently opened span
    if( substr_count($line, '<span') - substr_count($line, ' 0 )
    {
    $line .= '';

    // Grab colour to report it on next line
    $last_colour = explode('<span ',$line);
    $last_colour = $last_colour[count($last_colour)-1];

    $last_colour = substr($last_colour,strpos($last_colour,'#'),7);

    else $last_colour = NULL;

    echo '

  1. ',$line,"
  2. \r";
    }

    echo '

';
}

?>
SneakyWho_am_i 09-Sep-2008 09:00
From W on 20 August 2008:
YES! I do it too, on many of my things! I love to be able to share my code (when I have the right to do it) with friends who aren't working on the project.

I like to do it like this. The benefit is minimal but personally for such a small thing I would like to keep it down to one line. Maybe there is a shorter way, I don't know.. But the magic constant __FILE__ saves the day!

To access this one would be http://example.com/path/to/script.php?code
the parameter just has to be set (? or &) and you don't need the equals sign.
This way I don't generate any errors in E_ALL (because I'm likely in development), and I don't have to remember if the value was supposed to be "true" or "1" or "abacus" or whatever (I mean you're never going to specifically ask to NOT show the code, right?)

Anyway I've gone on long enough. It's nice to not be the only one who does this :D
W 19-Aug-2008 07:43
Normally I add highlighting for files like so:

In every file that should be higlighted:

And in highlight.inc.php (or your init file):

When a user will open the sourcecode (or you'll link to it) he just adds ?codeShow=1 to the filename.
mmcloughlin at gmail dot com 08-May-2008 11:06
You can trick this function to apply additional css rules to parts of the source code.

For example, if you wanted comments to appear in bold you could do the following

This works because when highlight_file() writes out a comment it wraps it in .... Therefore as long as your ini value for highlight.comment starts with a color, you can put in whatever style declarations you like.

This applies to all of the other relavent ini values: highlight.default, highlight.html, highlight.keyword, highlight.string.
comperr dot extra at gmail dot com 18-Apr-2008 04:20
Here is what I use

moisadoru at gmail dot com 16-Oct-2007 10:24
A function which parses the output of highlight file and replaces <span> wits <a>, replaces the style="color: #XXXXXX" part with class="cX", storing the colors in some css rules; that way you get a smaller output size (ratio is about about 1.2 ~ 1.4):

<?php
function highlight_file2($fl,$ret){
if(!isset($ret)) $ret = false;
$str = highlight_file($fl,true);
preg_match_all("/\.*?\/",$str,$mtch);
$m = array_unique($mtch[1]);

$cls = ''."\n";
$rpl = array("");
$mtc = array("");
$i = 0;
foreach($m as $clr) {
$cls .= "a.c".$i."{color: #".$clr.";}\n";
$rpl[] = "";
$mtc[] = "";
}
$cls .= "";
$str2 = str_replace($mtc,$rpl,$str);
if($ret) return $str2;
else echo $str2;
}
?>

thinbegin at unmannedship dot com 18-Aug-2007 03:45
i much prefer to use the .phps extension for showing highlighted source. all you have to do is type "cp example.php example.phps" at the command line.

on the flip side, for easy dynamic source sharing, it's as simple as:

<?php
if (!isset($_GET['file']) || trim($_GET['file']) == '') {
echo 'please pass me something yummy';
die(0);
}

if (!file_exists($_GET['file'])) {
echo "{$_GET['file']} does not seem to exist :(";
die(0);
}

highlight_file($_GET['file']);
?>
management at twilightus dot net 20-Mar-2007 11:18
Here's a better take at highlighting a file with line numbers:

.num {
float: left;
color: gray;
text-align: right;
margin-right: 6pt;
padding-right: 6pt;
border-right: 1px solid gray;}

<?php
function highlight_num($file)
{
echo '', implode(range(1, count(file($file))), '
'), '
';
highlight_file($file);
}

highlight_num('file.php');
?>

Thanks for the implode() part from Arevos at programmingforums.org
jens dot grasnick at gmail dot com 06-Oct-2006 11:38
Hi there, i build a "little" class to controll the highlighting functions (highlight_source & highlight_file) of PHP a little bit more. You can:

- set the highlighting colors without rewrite your php.ini
-create a whitelist using by highlightFile - so your're surly that nobody take a look on your private source😉
- work with the highlighted content - it returns the highlighted content, not show it like highlight_file or highlight_source did.

Class:

"",
"comment" => "",
"keyword" => "",
"bg" => "",
"default" => "",
"html" => "",
);

/* array of allowed file for using by ::highlightFile() */
private $whitelist = array();

/* construct */
function __construct($allowedFiles = NULL, /* array or NULL */
$newColors = NULL /* array or NULL */) {

/* add (if some given) files to the highlighting whitelist */
if($allowedFiles) {
$this -> addFiles($allowedFiles);
}

/* set highlighting colors */
if($newColors) {
$this -> setColors($newColors);
}
}

/* for adding files to the whitelist */
public function addFiles($allowedFiles /* array or string */) {
$file = is_array($allowedFiles) ? array_pop($allowedFiles) : $allowedFiles;

if(file_exists($file)) {
$this -> whitelist[] = $file;
} else

if(is_array($allowedFiles) && sizeof($allowedFiles)) {
$this -> addFiles($allowedFiles);
}

return void;
}

/* for setting new userColors */
public function setColors($newColors = array()) {
foreach($newColors as $key => $color) {
if(in_array($key, array_keys($this -> userColors))) {
$this -> userColors[$key] = $color;
}
}
}

/* replaces default colors with users colors */
private function putColors($highlightedContent) {
$nHC = $highlightedContent;
$hTpl = "";

foreach($this -> userColors as $key => $color) {
if(!empty($color)) {
$nHC = str_replace(sprintf($hTpl, ini_get("highlight.{$key}")), sprintf($hTpl, $color), $nHC);
}
}

return $nHC;
}

/* highlight's a string */
public function highlightString($string) {
$hC = "";

ob_start();
highlight_string($string);
$hC = ob_get_contents();
ob_end_clean();

return $this -> putColors($hC);
}

/* highlight's a file */
public function highlightFile($file) {
if(in_array($file, $this -> whitelist)) {
return $this -> highlightString(join("", file($file)));
}

return "";
}
}

?>

Usage:
$cl = new betterHighlighting([mixed files], [mixed colors]);

To put a file or a array of files to the whitelist, use (void) ::addFiles(mixed files).

To set a new color for highlighting use (void) ::setColors(array("string" => ..., "comment" => ..., "keyword" => ..., "bg" => ..., "default" => ..., "html" => ...)).
You only have to give the keyword(s), which color you'll change. If you only want to change the color of the highlighted comments, call ::setColors(array("comment" => "newcolor")) and so on.

Highlighting String:
(string)::highlightString(string $source)

Highlighting File:
(string)::highlightFile(string $file)

Note: The two last function RETURNS the highlighted content, not shows it directly.

Little example: I want to highlight the file "test.php" and the comments should be pink.

"pink"));

echo $cl -> highlightFile("test.php");

?>

Have fun.
paul at cheddar dot vaughany dot com 20-Aug-2006 09:53
It's a basic idea but one maybe worth sharing.

Save the script as showfile.php and access it like this:

Click here to see file 1 source code

The default case is for people editing the URL to try to access further files. Just don't add any files you don't want users to see, and maybe hard-code in large, random numbers or MD5 hashes.
showsource at gmail dot com 07-Apr-2006 10:18
Please, be aware of just using marlon at mbwp dot nl example to show the sourcecode
Do as told in this manual, "CAUTION", do some check on what code to highlight.
Simply just using $_GET["file"] is very bad.
marlon at mbwp dot nl 04-Mar-2006 09:06
I use the folowing code to highlight a file with line numbers:

<?php
echo "

";
for ($i = 1; $i <= count(file($_GET['file'])); $i++) echo $i.".
";
echo "
";
highlight_file($_GET['file']);
echo "

";
?>
msn at toolskyn dot nl 25-Feb-2006 05:18
I use this (simple and dirty) function in my tutorials to add linenumbers. I let all the linenumbers in one table cell so it is easier for people to copy and paste the code (so they don't have to remove all the linenumbers):

<?php
function highlight_with_linenum($file)
{
//open handle, set vars
$handle = fopen($file, "r");
$count = 1;
$lines = "";

//look line ends
while ($thisone = fread($handle, "1"))
{
if ($thisone == "\n")
{
//add number
$lines .= $count . "
";
$count++;
}
}
//close handle
fclose($handle);

//highlight contents
$contents = highlight_file($file, TRUE);

//print output (you could as well return now)
print '

' .
$lines . '
' .
$contents . '

';
}
?>

Maybe it's of use to someone
ganchev at design dot bg 12-Jan-2006 04:40
here's a simple way to add line numbers and
optionally highlight the one that has error on it.
just pass file and line arguments as GET variables

<?php

$f = fopen($_GET['file'], "r");
$count = 1;
$line = "";
echo "

";
while ($c = fread($f, "1")) {
$line .= $c;
if ($c == "\n") {
echo "

\n";
$line = "";
$count++;
}
}
echo "

$count. " . highlight_string($line, TRUE) . "

";
fclose($f);

?>
dtroi50 at gmail dot com 09-Jan-2006 06:39
If you run a site that has PHP script examples and you want to show the source, instead of a phps file, just add the following code to the top of the script.

Then to make a source link use this:

<?php
print'Show source';
?>

Note that you don't have to use souce. If any get variables are set, it'll work.

-Tom
venski at gmail dot com 05-Jan-2006 09:21
I think it will be better if the variable contains the files that are allowed to be viewed. There can always befound a way to pass the name of a forbiddedn file that is not in the prohibited array.

Thus the code will be:

trukin at gmail dot com 08-Dec-2005 11:46
this function can be a high security risk. use something like in_array to check if a file is prohibited to be shown on screen.

Michael Newton (http://mike.eire.ca/) 06-Dec-2005 01:48
To print out the current file:

Useful to add this as a header to all scripts (during development only, of course!)

Vlad Alexa Mancini valexa at nextcode dot org 21-Feb-2005 03:19
Here is a small bash script that you can type at the console to make recursive symbolic .phps links for all your .php files starting at your curent directory

for f in `find -name '*.php'`; do ln -s `basename $f` $f's'; done

NOTE: You doubtedly want to do this at / as it will make such symlinks for all the php files on your filesystem

NOTE: This places the symlinks in the same directory as the php file that they are simlinking

And a simpler one that is not recursive and does the same thing but only for the php files in your current directory

for f in *.php; do ln -s $f $f's'; done

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s