Php syntax highlight file

PHP highlight_file() Function

Using a test file («test.php») to output the file with the PHP syntax highlighted:

The browser output of the code above could be (depending on the content in your file):

The HTML output of the code above could be (View Source):

Definition and Usage

The highlight_file() function outputs a file with the PHP syntax highlighted. The syntax is highlighted by using HTML tags.

Tip: The colors used for syntax highlighting can be set in the php.ini file or with the ini_set() function.

Note: When using this function, the entire file will be displayed — including passwords and any other sensitive information!

Syntax

Parameter Values

Parameter Description
filename Required. Specifies the file to be highlighted
return Optional. If set to TRUE, this function will return the highlighted code as a string, instead of printing it out. Default is FALSE

Technical Details

Return Value: If the return parameter is set to TRUE, this function returns the highlighted code as a string instead of printing it out. Otherwise, it returns TRUE on success, or FALSE on failure
PHP Version: 4+
Changelog: PHP 4.2.1 — This function is now also affected by safe_mode and open_basedir. However, safe_mode was deprecated and removed in PHP 5.4.
PHP 4.2 — The return parameter was added.

❮ PHP Misc Reference

Читайте также:  Java programming for gui

Источник

highlight_file

Выводит или возвращает версию с подсветкой синтаксиса кода, содержащегося в файле filename , используя цвета определенные во встроенной подсветке синтаксиса PHP.

Большинство серверов сконфигурированы автоматически подсвечивать файлы с расширением phps. К примеру, при отображении файла example.phps будет выведен код с подсветкой синтаксиса. Для включения добавьте следующую строку в httpd.conf :

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

Список параметров

Путь к подсвечиваемому PHP файлу.

Установите в этот параметр TRUE для того чтобы функция возвращала подсвеченный код.

Возвращаемые значения

Если в return установлено TRUE , то подсвеченный код возвращается в виде строки, а не отображается. В другом случае будет возвращено TRUE , либо FALSE при ошибке.

Список изменений

Версия Описание
4.2.1 На данный момент на эту функцию также воздействуют режимы safe_mode и open_basedir.

Примечания

Необходимо пользоваться функцией highlight_file() с должным вниманием, с тем чтобы по неосторожности не раскрыть конфиденциальную информацию, такую как пароли или любую другую информацию, которая может создать потенциальную угрозу безопасности.

Замечание:

При использовании параметра return данная функция использует внутреннюю буферизацию вывода, поэтому она не может быть использована внутри callback-функции ob_start() .

Смотрите также

Источник

highlight_file

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf :

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

Parameters

Path to the PHP file to be highlighted.

Set this parameter to true to make this function return the highlighted code.

Return Values

If return is set to true , returns the highlighted code as a string instead of printing it out. Otherwise, it will return true on success, false on failure.

Notes

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

See Also

User Contributed Notes 23 notes

This is my try on linenumbers
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 );

//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 );
>

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

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 ‘ . $line . ‘

‘ . «\r\n» ;
else
echo ‘

. $startcolor . ‘;»>’ . $line . ‘

‘ . «\r\n» ;

Источник

highlight_file

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf :

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

Parameters

Path to the PHP file to be highlighted.

Set this parameter to true to make this function return the highlighted code.

Return Values

If return is set to true , returns the highlighted code as a string instead of printing it out. Otherwise, it will return true on success, false on failure.

Notes

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

See Also

  • Misc. Functions
    • connection_​aborted
    • connection_​status
    • constant
    • define
    • defined
    • die
    • eval
    • exit
    • get_​browser
    • _​_​halt_​compiler
    • highlight_​file
    • highlight_​string
    • hrtime
    • ignore_​user_​abort
    • pack
    • php_​strip_​whitespace
    • sapi_​windows_​cp_​conv
    • sapi_​windows_​cp_​get
    • sapi_​windows_​cp_​is_​utf8
    • sapi_​windows_​cp_​set
    • sapi_​windows_​generate_​ctrl_​event
    • sapi_​windows_​set_​ctrl_​handler
    • sapi_​windows_​vt100_​support
    • show_​source
    • sleep
    • sys_​getloadavg
    • time_​nanosleep
    • time_​sleep_​until
    • uniqid
    • unpack
    • usleep

    Источник

Оцените статью