PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

highlight_string> <__halt_compiler
Last updated: Fri, 04 Jul 2008

view this page in

highlight_file

(PHP 4, PHP 5)

highlight_file — ファイルの構文ハイライト表示

説明

mixed highlight_file ( string $filename [, bool $return ] )

filename の中のコードを構文ハイライト表示して 出力します。色は、PHP 組込の構文ハイライタで定義されているものを使用します。

多くのサーバでは、拡張子が phps のファイルは 自動的に構文ハイライト表示されるように設定されています。例えば example.phps のようなファイルは、構文ハイライト したソースファイルとして表示されます。これを有効にするには、 httpd.conf に以下のような行を追加します。

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

パラメータ

filename

ハイライト表示する PHP ファイルへのパス。

return

このパラメータを TRUE にすると、この関数はハイライトされたコードを返します。

返り値

returnTRUE の場合は、 ハイライトされたコードを文字列として返し、表示しません。 それ以外の場合は、成功した場合に TRUE、 失敗した場合に FALSE を返します。

変更履歴

バージョン 説明
4.2.1 この関数は safe_mode および open_basedir の影響を受けます。
4.2.0 パラメータ return が追加されました。

注意

警告

highlight_file() 関数を使用する場合には、 パスワードやその他潜在的なセキュリティ上の危険を生む類の重要な 情報を不注意で公開してしまわないように注意する必要があります。

注意: この関数は、 このパラメータに対して内部的に出力バッファリングを使用しています。 そのため、ob_start() コールバック関数の中で使用することはできません。



highlight_string> <__halt_compiler
Last updated: Fri, 04 Jul 2008
 
add a note add a note User Contributed Notes
highlight_file
mmcloughlin at gmail dot com
09-May-2008 10: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

<?php
ini_set
('highlight.comment', '#CCCCCC; font-weight: bold;');
highlight_file('file.php');
?>

This works because when highlight_file() writes out a comment it wraps it in <span style="color: {contents of hightlight.comment ini variable}">...</span>. 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
19-Apr-2008 03:20
Here is what I use
<?php

   
/* array() ensures that ok[] cannot have paths inserted if register globals is enabled */

   
$ok = array(
       
'f1.php',
       
'f2.php'
   
);

    if (!
in_array($_GET['f'], $ok))
    {
        die (
'Not allowed to view this page');
    }
    else
    {
       
highlight_file($_GET['f']);
    }
?>
moisadoru at gmail dot com
17-Oct-2007 09:24
A function which parses the output of highlight file and replaces &lt;span&gt; wits &lt;a&gt;, 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):
<code>
<?php
function highlight_file2($fl,$ret){
    if(!isset(
$ret)) $ret = false;
   
$str = highlight_file($fl,true);
   
preg_match_all("/\<span style=\"color: #([\d|A|B|C|D|E|F]{6})\"\>.*?\<\/span\>/",$str,$mtch);
   
$m = array_unique($mtch[1]);

   
$cls = '<style type="text/css">'."\n";
   
$rpl = array("</a>");
   
$mtc = array("</span>");
   
$i = 0;
    foreach(
$m as $clr) {
       
$cls .= "a.c".$i."{color: #".$clr.";}\n";
       
$rpl[] = "<a class=\"c".$i++."\">";
       
$mtc[] = "<span style=\"color: #".$clr."\">";
    }
   
$cls .= "</style>";
   
$str2 = str_replace($mtc,$rpl,$str);
    if(
$ret) return $str2;
    else echo
$str2;
}
?>
</code>
thinbegin at unmannedship dot com
19-Aug-2007 02: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
"<b>{$_GET['file']}</b> does not seem to exist :(";
    die(
0);
}

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

<style type="text/css">
.num {
float: left;
color: gray;
text-align: right;
margin-right: 6pt;
padding-right: 6pt;
border-right: 1px solid gray;}
</style>
<?php
function highlight_num($file)
{
  echo
'<code class="num">', implode(range(1, count(file($file))), '<br />'), '</code>';
 
highlight_file($file);
}

highlight_num('file.php');
?>

Thanks for the implode() part from Arevos at programmingforums.org
jens dot grasnick at gmail dot com
07-Oct-2006 10: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:

<?php

class betterHighlighting {
 
/* user colors */
 
private $userColors = array(
     
"string"  => "",
     
"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 = "<span style=\"color: %s\">";
   
    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.

<?php

$cl
= betterHighlighting("test.php", array("comment" => "pink"));

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

?>

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

<?php
switch($_GET['file']) {
    case
1:
       
highlight_file("file1.php");
        break;
    case
2:
       
highlight_file("file2.php");
        break;
    case
3:
       
highlight_file("file3.php");
        break;
    default:
       
header("Location: ".$_SERVER["PHP_SELF"]);
}
?>

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

<a href="showfile.php?file=1">Click here to see file 1 source code</a>

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
08-Apr-2006 09: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
05-Mar-2006 10:06
I use the folowing code to highlight a file with line numbers:

<?php
echo "<table bgcolor=#EEEEEE><tr><td width=30>";
for (
$i = 1; $i <= count(file($_GET['file'])); $i++) echo $i.".<br>";
echo
"</td><td>";
highlight_file($_GET['file']);
echo
"</td></tr></table>";
?>
msn at toolskyn dot nl
26-Feb-2006 06: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 . "<br />";
           
$count++;
        }
    }   
   
//close handle
   
fclose($handle);

   
//highlight contents
   
$contents = highlight_file($file, TRUE);
       
   
//print output (you could as well return now)
   
print '<table><tr><td><code>' .
         
$lines . '</code></td><td>' .
         
$contents . '</td></tr></table>';   
}
?>

Maybe it's of use to someone
ganchev at design dot bg
13-Jan-2006 05: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
"<table>";
while (
$c = fread($f, "1")) {
 
$line .= $c;
  if (
$c == "\n") {
    echo
"<tr style='background: " . (($_GET['line'] == $count) ? "#eedddd" : "#ffffff") . "'><td width='10%'>$count.</td><td>" . highlight_string($line, TRUE) . "</td></tr>\n";
   
$line = "";
   
$count++;
  }
}
echo
"</table>";
fclose($f);

?>
dtroi50 at gmail dot com
10-Jan-2006 07: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.

<?php
if(count($_GET)) {
highlight_file(__FILE__);
}
?>

Then to make a source link use this:

<?php
print'<a href="?source">Show source</a>';
?>

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

-Tom
venski at gmail dot com
06-Jan-2006 10: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:

<?php
//array with files to allow
$allowed = array('index.php', 'menu.php', 'about.php');

// get the filename
$file = $_GET[file];
if(
file_Exists($file)){
    if(
in_array($file, $allowed)){
       
// check if it is part of the allowed list
       
highlight_file($file); //highlight file
   
}
    else{
       
// not allowed. just die. do not warn ;)
       
die("");
    }
}
else{
   
// file doesnt exist
   
echo "The file does not exist.";      
}
?>
trukin at gmail dot com
09-Dec-2005 12: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.

<?
$ar
= array('config.php', 'index.php', 'functions.php');    //array with files to denie
$file = $_GET[file];                    // iniziate the variable
if(file_Exists($file)){
    if(!
in_array($file, $ar)){    // check if it is prohibited
       
highlight_file($file); //highlight file
   
}else{     // prohibited file
       
echo "You do not have permision to see the ".$file." file.";
    }
}else{   
// file doesnt exist
   
echo "That file does not exist.";       
}
?>
Michael Newton (http://mike.eire.ca/)
07-Dec-2005 02:48
To print out the current file:

<?php highlight_file( __FILE__ ); ?>

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

<?php
if ($_GET['debug']) {
   
highlight_file( __FILE__ );
    exit;
}
?>
Vlad Alexa Mancini valexa at nextcode dot org
22-Feb-2005 04: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
aidan at php dot net
27-Sep-2004 12:29
To add line numbers to source code, with optional function linking, use the below function:

http://aidanlister.com/repos/v/function.highlight_file_linenum.php

A much more thorough and smarter, though slower version is here:

http://aidanlister.com/repos/v/PHP_Highlight.php
csst0266 at cs dot uoi dot gr
14-Aug-2004 01:42
Here is a simple, yet useful, tip... Issuing the following command under a Unix-like OS:

ln -s your_script.php your_script.phps

Will result in the creation of a symbolic link (called your_script.phps) to the source code (your_script.php). This way you have (apart from the source code .php) the highlighted version of your script (.phps) accessible via your web browser.
zan at stargeek dot com
09-Jan-2003 03:24
here's how to use highlight_file to create a browseable archive of php scripts http://www.stargeek.com/scripts.php?script=7&cat=blog

highlight_string> <__halt_compiler
Last updated: Fri, 04 Jul 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites