Current Location: Home> Latest Articles> How to use highlight_file to output syntax highlighting of PHP files

How to use highlight_file to output syntax highlighting of PHP files

gitbox 2025-05-26

What is the highlight_file function?

highlight_file is a function provided by PHP, which is used to output the specified PHP file content in syntax highlighting. It will automatically add colors to keywords, variables, strings, etc., thereby improving the readability of the code. This function can output highlighted content directly or choose to return it as a string.

The function prototype is as follows:

 highlight_file(string $filename, bool $return = false): string|bool
  • $filename : The path to the PHP file to be read and highlighted.

  • $return : Whether to return highlighted content instead of direct output, default is false .


Use highlight_file to achieve basic syntax highlighting

Here is a basic example for highlighting the contents of the current script itself:

 <?php
highlight_file(__FILE__);
?>

Save the above code as a .php file and access it in the browser, and you can see the source code output with color.


How to highlight other PHP files

If you want the user to specify the file to view through URL parameters (such as a PHP file in the code directory), you can refer to the following example:

 <?php
$filename = $_GET['file'] ?? '';

$allowed_files = [
    'example1.php',
    'example2.php'
];

if (in_array($filename, $allowed_files)) {
    highlight_file(__DIR__ . '/' . $filename);
} else {
    echo 'Illegal file request。';
}
?>

You can access the highlighted page of the file content in the following ways:

 https://gitbox.net/highlight.php?file=example1.php

Note: **For security reasons, never use the path provided by the user to read files directly. **The above code limits only allowing viewing of specific files to prevent security risks such as directory traversal attacks.


Return string and customize display method

If you want to control the display more flexibly (such as adding CSS styles and wrapping them in a specific HTML structure), you can return the highlighted content as a string by setting the $return parameter to true :

 <?php
$highlighted = highlight_file('example1.php', true);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Code highlighting</title>
    <style>
        body {
            background-color: #f0f0f0;
            font-family: monospace;
        }
        .code-box {
            background-color: #fff;
            padding: 20px;
            border: 1px solid #ddd;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <h2>example1.php Code display</h2>
    <div class="code-box">
        <?php echo $highlighted; ?>
    </div>
</body>
</html>

This method is more suitable for custom display styles, such as combining front-end frames, beautifying typesetting, etc.