- PHP highlight_file() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- highlight_file
- Список параметров
- Возвращаемые значения
- Список изменений
- Примечания
- Смотрите также
- highlight_file
- Parameters
- Return Values
- Notes
- See Also
- User Contributed Notes 23 notes
- highlight_file
- Parameters
- Return Values
- Notes
- See Also
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
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 ‘
‘ . «\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