[PHP]show_source()完全解説|ソースコードのシンタックスハイライト表示とhighlight_file()との関係

PHP

はじめに

PHPファイルのソースコードをブラウザ上でシンタックスハイライト付きで表示したい場面があります。ドキュメント生成・コードレビューツール・学習用サンプル表示・デバッグ支援など、コードを人間が読みやすい形で出力する用途です。

show_source() はPHPファイルをシンタックスカラーリングしてHTMLとして出力する関数です。実は highlight_file() の**エイリアス(別名)**であり、完全に同じ動作をします。シンプルで即使えますが、公開環境での誤用はソースコード漏洩という深刻なセキュリティリスクになるため、使いどころを正しく理解することが重要です。


関数の概要

項目内容
関数名show_source()
別名highlight_file() の完全なエイリアス
所属PHP 文字列関数
導入バージョンPHP 4以降
PHP 8.x対応済み

構文

show_source(string $filename, bool $return = false): string|true|false

highlight_file() と完全に同じシグネチャです。

パラメータ

パラメータデフォルト説明
$filenamestring(必須)ハイライト表示するPHPファイルのパス
$returnboolfalsetrue にすると出力せずHTML文字列として返す

戻り値

$return成功時失敗時
false(デフォルト)true を返し、HTMLを出力するfalse
trueハイライト済みHTML文字列を返すfalse

show_source() と highlight_file() の関係

<?php
// この2つは完全に同じ動作をする
show_source('script.php');
highlight_file('script.php');

// どちらも同じHTML文字列を返す
$html1 = show_source('script.php', true);
$html2 = highlight_file('script.php', true);
var_dump($html1 === $html2); // bool(true)

show_source()highlight_file() の別名として提供されており、どちらを使っても挙動は同一です。コードベースの統一感から highlight_file() を使うプロジェクトが多いですが、show_source() はより意味が直感的という観点から好まれることもあります。


関連関数

関数対象説明
show_source() / highlight_file()ファイルPHPファイルをハイライト表示
highlight_string()文字列PHP コード文字列をハイライト表示
php_strip_whitespace()ファイルホワイトスペースとコメントを除去したソースを返す

出力されるHTML の構造

show_source('example.php');

出力例(簡略):

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php<br /></span>
<span style="color: #007700">echo&nbsp;</span>
<span style="color: #DD0000">'Hello'</span>
<span style="color: #007700">;</span>
</span>
</code>

デフォルトの配色は php.inihighlight.* ディレクティブで制御されています。

デフォルトの配色設定

php.ini ディレクティブデフォルト色対象
highlight.comment#FF8000コメント
highlight.default#0000BBデフォルト(変数名など)
highlight.html#000000HTML部分
highlight.keyword#007700キーワード・演算子
highlight.string#DD0000文字列

基本的な使い方

<?php
// ファイルをシンタックスハイライト付きで出力する
show_source(__FILE__); // 自分自身を表示

// HTML文字列として取得する(出力しない)
$html = show_source('target.php', true);
echo strlen($html) . " バイトのHTMLを生成しました\n";

// ファイルが存在しない場合
$result = show_source('nonexistent.php');
var_dump($result); // bool(false)

実践的なクラスベースの使用例

例1:安全なソースコードビューアクラス

<?php
/**
 * 許可されたファイルのみを表示する安全なソースコードビューアクラス
 * パストラバーサル攻撃やアクセス制御を考慮した実装
 */
class SecureSourceViewer
{
    private array  $allowedPaths;
    private array  $allowedExtensions;

    public function __construct(
        array $allowedPaths      = [],
        array $allowedExtensions = ['php']
    ) {
        // realpath で正規化してシンボリックリンクも解決する
        $this->allowedPaths      = array_map('realpath', array_filter($allowedPaths, 'is_dir'));
        $this->allowedExtensions = array_map('strtolower', $allowedExtensions);
    }

    /**
     * ファイルを安全にハイライト表示する
     */
    public function display(string $requestedPath): bool
    {
        try {
            $safePath = $this->validate($requestedPath);
        } catch (\RuntimeException $e) {
            echo "<p style='color:red'>エラー: {$e->getMessage()}</p>\n";
            return false;
        }

        echo "<div class='source-viewer'>\n";
        echo "<h3>" . htmlspecialchars(basename($safePath)) . "</h3>\n";
        $result = show_source($safePath);
        echo "</div>\n";

        return $result !== false;
    }

    /**
     * HTML文字列として取得する
     */
    public function getHighlighted(string $requestedPath): string
    {
        $safePath = $this->validate($requestedPath);
        $html     = show_source($safePath, return: true);

        if ($html === false) {
            throw new \RuntimeException("ファイルの読み込みに失敗しました: {$safePath}");
        }

        return $html;
    }

    /**
     * パスを検証してセーフなパスを返す
     */
    private function validate(string $path): string
    {
        // realpath でパストラバーサル(../)を解決
        $realPath = realpath($path);

        if ($realPath === false) {
            throw new \RuntimeException("ファイルが見つかりません: {$path}");
        }

        if (!is_file($realPath)) {
            throw new \RuntimeException("通常ファイルではありません: {$realPath}");
        }

        // 拡張子チェック
        $ext = strtolower(pathinfo($realPath, PATHINFO_EXTENSION));
        if (!in_array($ext, $this->allowedExtensions, true)) {
            throw new \RuntimeException("許可されていない拡張子です: .{$ext}");
        }

        // 許可されたパス配下かチェック(パストラバーサル対策)
        if (!empty($this->allowedPaths)) {
            $allowed = false;
            foreach ($this->allowedPaths as $allowedPath) {
                if (str_starts_with($realPath, $allowedPath . DIRECTORY_SEPARATOR)) {
                    $allowed = true;
                    break;
                }
            }
            if (!$allowed) {
                throw new \RuntimeException("許可されたディレクトリ外のファイルです");
            }
        }

        return $realPath;
    }
}

$viewer = new SecureSourceViewer(
    allowedPaths:      ['/var/www/myapp/public/examples'],
    allowedExtensions: ['php']
);

// $viewer->display('/var/www/myapp/public/examples/hello.php');
// $viewer->display('../../config/database.php'); // ← RuntimeException が発生する

例2:ドキュメント生成クラス

<?php
/**
 * PHP ファイルのソースコードと docblock コメントを組み合わせて
 * ドキュメントページを生成するクラス
 * show_source() でコードを表示しつつファイル情報も付加する
 */
class SourceDocumentGenerator
{
    public function generate(string $filePath, array $options = []): string
    {
        $opts = array_merge([
            'show_stats'    => true,
            'show_docblock' => true,
            'wrap_in_html'  => true,
        ], $options);

        if (!is_file($filePath)) {
            throw new \InvalidArgumentException("ファイルが存在しません: {$filePath}");
        }

        $html  = '';

        if ($opts['wrap_in_html']) {
            $html .= $this->htmlHeader(basename($filePath));
        }

        // ファイル情報ヘッダー
        if ($opts['show_stats']) {
            $html .= $this->renderStats($filePath);
        }

        // Docblock の抽出・表示
        if ($opts['show_docblock']) {
            $docblock = $this->extractDocblock($filePath);
            if ($docblock) {
                $html .= $this->renderDocblock($docblock);
            }
        }

        // ソースコードのハイライト
        $highlighted = show_source($filePath, return: true);
        if ($highlighted === false) {
            throw new \RuntimeException("ハイライト生成に失敗しました");
        }

        $html .= "<div class='source-code'>\n{$highlighted}\n</div>\n";

        if ($opts['wrap_in_html']) {
            $html .= $this->htmlFooter();
        }

        return $html;
    }

    private function renderStats(string $filePath): string
    {
        $lines    = count(file($filePath));
        $size     = filesize($filePath);
        $modified = date('Y-m-d H:i:s', filemtime($filePath));
        $name     = htmlspecialchars(basename($filePath));

        return <<<HTML
        <div class='file-stats'>
            <h2>{$name}</h2>
            <table>
                <tr><th>行数</th><td>{$lines} 行</td></tr>
                <tr><th>サイズ</th><td>{$size} バイト</td></tr>
                <tr><th>更新日時</th><td>{$modified}</td></tr>
            </table>
        </div>
        HTML;
    }

    private function extractDocblock(string $filePath): ?string
    {
        $content = file_get_contents($filePath);
        if (preg_match('/\/\*\*(.*?)\*\//s', $content, $matches)) {
            return trim($matches[1]);
        }
        return null;
    }

    private function renderDocblock(string $docblock): string
    {
        $lines = array_map('trim', explode("\n", $docblock));
        $clean = array_filter(array_map(fn($l) => ltrim($l, '* '), $lines));
        $text  = htmlspecialchars(implode("\n", $clean));
        return "<div class='docblock'><pre>{$text}</pre></div>\n";
    }

    private function htmlHeader(string $title): string
    {
        $title = htmlspecialchars($title);
        return <<<HTML
        <!DOCTYPE html>
        <html lang="ja">
        <head>
            <meta charset="UTF-8">
            <title>{$title}</title>
            <style>
                body { font-family: monospace; margin: 20px; }
                .file-stats table { border-collapse: collapse; }
                .file-stats td, .file-stats th { padding: 4px 12px; border: 1px solid #ccc; }
                .docblock { background: #f0f0f0; padding: 12px; border-left: 4px solid #666; }
                .source-code { background: #fafafa; border: 1px solid #ddd; padding: 8px; }
            </style>
        </head>
        <body>
        HTML;
    }

    private function htmlFooter(): string
    {
        return "</body></html>\n";
    }
}

$generator = new SourceDocumentGenerator();
// $html = $generator->generate('/app/src/MyClass.php');
// file_put_contents('/app/docs/MyClass.html', $html);
// echo "ドキュメント生成完了\n";

例3:複数ファイルのコードブラウザクラス

<?php
/**
 * ディレクトリ内の PHP ファイルを一覧表示して
 * 選択したファイルのソースを show_source() で表示するクラス
 * 学習環境・コードレビューツール向け
 */
class CodeBrowser
{
    private string $rootDir;
    private array  $excludePatterns;

    public function __construct(
        string $rootDir,
        array  $excludePatterns = ['vendor', 'node_modules', '.git']
    ) {
        $realRoot = realpath($rootDir);
        if ($realRoot === false || !is_dir($realRoot)) {
            throw new \InvalidArgumentException("有効なディレクトリではありません: {$rootDir}");
        }
        $this->rootDir         = $realRoot;
        $this->excludePatterns = $excludePatterns;
    }

    /**
     * ディレクトリ内の PHP ファイル一覧を取得する
     */
    public function listFiles(): array
    {
        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator(
                $this->rootDir,
                \RecursiveDirectoryIterator::SKIP_DOTS
            )
        );

        $files = [];
        foreach ($iterator as $file) {
            if ($file->getExtension() !== 'php') {
                continue;
            }

            $path = $file->getRealPath();

            // 除外パターンのチェック
            $skip = false;
            foreach ($this->excludePatterns as $pattern) {
                if (str_contains($path, DIRECTORY_SEPARATOR . $pattern . DIRECTORY_SEPARATOR)
                    || str_ends_with($path, DIRECTORY_SEPARATOR . $pattern)) {
                    $skip = true;
                    break;
                }
            }
            if ($skip) continue;

            $relative = str_replace($this->rootDir . DIRECTORY_SEPARATOR, '', $path);
            $files[]  = [
                'path'     => $path,
                'relative' => $relative,
                'size'     => $file->getSize(),
                'lines'    => count(file($path)),
            ];
        }

        usort($files, fn($a, $b) => strcmp($a['relative'], $b['relative']));
        return $files;
    }

    /**
     * ファイル一覧をHTMLで出力する
     */
    public function renderFileList(): string
    {
        $files = $this->listFiles();
        $html  = "<ul class='file-list'>\n";

        foreach ($files as $file) {
            $name  = htmlspecialchars($file['relative']);
            $lines = $file['lines'];
            $size  = number_format($file['size']);
            $html .= "  <li>{$name} ({$lines}行 / {$size}B)</li>\n";
        }

        $html .= "</ul>\n";
        $html .= "<p>合計: " . count($files) . " ファイル</p>\n";
        return $html;
    }

    /**
     * 指定ファイルのソースを安全に表示する
     */
    public function displayFile(string $relativePath): bool
    {
        // パストラバーサル対策
        $fullPath = realpath($this->rootDir . DIRECTORY_SEPARATOR . $relativePath);

        if ($fullPath === false || !str_starts_with($fullPath, $this->rootDir)) {
            echo "<p>アクセス拒否: {$relativePath}</p>\n";
            return false;
        }

        if (!is_file($fullPath) || pathinfo($fullPath, PATHINFO_EXTENSION) !== 'php') {
            echo "<p>無効なファイル: {$relativePath}</p>\n";
            return false;
        }

        echo "<h3>" . htmlspecialchars($relativePath) . "</h3>\n";
        return show_source($fullPath) !== false;
    }
}

// $browser = new CodeBrowser('/var/www/myapp/src');
// echo $browser->renderFileList();
// $browser->displayFile('Model/User.php');

例4:差分ハイライト比較クラス

<?php
/**
 * 2つのPHPファイルのソースコードを並べて表示するクラス
 * show_source() で両ファイルをハイライトして比較しやすくする
 */
class SourceDiffViewer
{
    /**
     * 2ファイルを横並びで表示する
     */
    public function sideBySide(string $file1, string $file2): string
    {
        $this->assertReadable($file1);
        $this->assertReadable($file2);

        $html1 = show_source($file1, return: true);
        $html2 = show_source($file2, return: true);

        $name1 = htmlspecialchars(basename($file1));
        $name2 = htmlspecialchars(basename($file2));

        $lines1 = count(file($file1));
        $lines2 = count(file($file2));
        $diff   = $lines2 - $lines1;
        $diffStr = $diff > 0 ? "+{$diff}" : (string) $diff;
        $diffColor = $diff > 0 ? 'green' : ($diff < 0 ? 'red' : 'gray');

        return <<<HTML
        <div style="display:flex; gap:16px;">
            <div style="flex:1; overflow:auto;">
                <h4>{$name1}({$lines1}行)</h4>
                {$html1}
            </div>
            <div style="flex:1; overflow:auto;">
                <h4>{$name2}({$lines2}行)
                    <span style="color:{$diffColor}">({$diffStr}行)</span>
                </h4>
                {$html2}
            </div>
        </div>
        HTML;
    }

    /**
     * 行数・サイズ・変更時刻の差分サマリを返す
     */
    public function summary(string $file1, string $file2): array
    {
        $this->assertReadable($file1);
        $this->assertReadable($file2);

        $lines1 = count(file($file1));
        $lines2 = count(file($file2));
        $size1  = filesize($file1);
        $size2  = filesize($file2);

        return [
            'file1'       => basename($file1),
            'file2'       => basename($file2),
            'lines_diff'  => $lines2 - $lines1,
            'size_diff'   => $size2 - $size1,
            'newer'       => filemtime($file1) > filemtime($file2)
                ? basename($file1)
                : basename($file2),
        ];
    }

    private function assertReadable(string $path): void
    {
        if (!is_file($path) || !is_readable($path)) {
            throw new \InvalidArgumentException("ファイルを読み込めません: {$path}");
        }
        if (pathinfo($path, PATHINFO_EXTENSION) !== 'php') {
            throw new \InvalidArgumentException("PHPファイルではありません: {$path}");
        }
    }
}

$viewer = new SourceDiffViewer();
// $html = $viewer->sideBySide('/app/src/v1/User.php', '/app/src/v2/User.php');
// echo $html;
// print_r($viewer->summary('/app/src/v1/User.php', '/app/src/v2/User.php'));

例5:ハイライトカラーカスタマイズクラス

<?php
/**
 * php.ini の highlight.* 設定を実行時に変更して
 * カスタムカラースキームでソースをハイライト表示するクラス
 * ini_set() で一時的に配色を変更し、表示後に元に戻す
 */
class CustomHighlightTheme
{
    private array $themes = [
        'default' => [
            'highlight.comment' => '#FF8000',
            'highlight.default' => '#0000BB',
            'highlight.html'    => '#000000',
            'highlight.keyword' => '#007700',
            'highlight.string'  => '#DD0000',
        ],
        'dark' => [
            'highlight.comment' => '#75715E',
            'highlight.default' => '#66D9EF',
            'highlight.html'    => '#F8F8F2',
            'highlight.keyword' => '#F92672',
            'highlight.string'  => '#E6DB74',
        ],
        'solarized' => [
            'highlight.comment' => '#93A1A1',
            'highlight.default' => '#268BD2',
            'highlight.html'    => '#657B83',
            'highlight.keyword' => '#859900',
            'highlight.string'  => '#2AA198',
        ],
        'github' => [
            'highlight.comment' => '#6A737D',
            'highlight.default' => '#005CC5',
            'highlight.html'    => '#24292E',
            'highlight.keyword' => '#D73A49',
            'highlight.string'  => '#032F62',
        ],
    ];

    /**
     * 指定テーマでファイルをハイライトして HTML 文字列を返す
     */
    public function highlight(string $filePath, string $theme = 'default'): string
    {
        if (!isset($this->themes[$theme])) {
            throw new \InvalidArgumentException("未定義のテーマ: {$theme}");
        }

        // 現在の配色を保存
        $saved = [];
        foreach ($this->themes[$theme] as $key => $_) {
            $saved[$key] = ini_get($key);
        }

        // テーマを適用
        foreach ($this->themes[$theme] as $key => $color) {
            ini_set($key, $color);
        }

        // ハイライト生成
        $html = show_source($filePath, return: true);

        // 元の配色に戻す
        foreach ($saved as $key => $value) {
            ini_set($key, $value);
        }

        if ($html === false) {
            throw new \RuntimeException("ハイライト生成失敗: {$filePath}");
        }

        $bg = $theme === 'dark' ? '#272822' : ($theme === 'solarized' ? '#FDF6E3' : '#FFFFFF');
        return "<div style='background:{$bg}; padding:8px;'>{$html}</div>";
    }

    /**
     * カスタムテーマを追加する
     */
    public function addTheme(string $name, array $colors): void
    {
        $required = ['highlight.comment', 'highlight.default', 'highlight.html',
                     'highlight.keyword', 'highlight.string'];
        foreach ($required as $key) {
            if (!isset($colors[$key])) {
                throw new \InvalidArgumentException("テーマに必要なキーが不足: {$key}");
            }
        }
        $this->themes[$name] = $colors;
        echo "テーマ追加: {$name}\n";
    }

    public function getAvailableThemes(): array
    {
        return array_keys($this->themes);
    }
}

$highlighter = new CustomHighlightTheme();
echo "利用可能テーマ: " . implode(', ', $highlighter->getAvailableThemes()) . "\n";
// $html = $highlighter->highlight('/app/src/MyClass.php', theme: 'dark');
// echo $html;

例6:CLI 向けソース表示クラス

<?php
/**
 * CLI 環境で show_source() の HTML 出力をプレーンテキストに変換するクラス
 * ターミナルで PHP ファイルの内容を確認するのに使用する
 * ANSI カラーコードで色付け表示もサポートする
 */
class CliSourceDisplay
{
    // ANSI カラーコード(html の color 属性から変換)
    private array $colorMap = [
        '#FF8000' => "\033[33m",   // コメント → 黄色
        '#0000BB' => "\033[34m",   // デフォルト → 青
        '#000000' => "\033[37m",   // HTML → 白
        '#007700' => "\033[32m",   // キーワード → 緑
        '#DD0000' => "\033[31m",   // 文字列 → 赤
    ];
    private string $reset  = "\033[0m";

    /**
     * PHP ファイルをターミナルに色付きで表示する
     */
    public function display(string $filePath, bool $colorize = true): void
    {
        if (!is_file($filePath) || !is_readable($filePath)) {
            echo "ファイルを読み込めません: {$filePath}\n";
            return;
        }

        $html = show_source($filePath, return: true);
        if ($html === false) {
            echo "ハイライト生成失敗\n";
            return;
        }

        $plain = $this->htmlToPlain($html, $colorize);

        echo "=== " . basename($filePath) . " ===\n";
        echo $plain;
        echo "\n=== " . count(file($filePath)) . " 行 ===\n";
    }

    /**
     * show_source() の HTML 出力をプレーンテキスト(ANSI付き)に変換する
     */
    private function htmlToPlain(string $html, bool $colorize): string
    {
        if ($colorize) {
            // <span style="color: #XXXXXX"> を ANSI コードに変換
            $result = preg_replace_callback(
                '/<span style="color: (#[0-9A-Fa-f]+)">(.*?)<\/span>/s',
                function (array $m): string {
                    $ansi = $this->colorMap[strtoupper($m[1])] ?? '';
                    return $ansi . html_entity_decode(strip_tags($m[2])) . $this->reset;
                },
                $html
            );
        } else {
            $result = $html;
        }

        // 残った HTML タグと実体参照を除去
        $result = strip_tags($result ?? $html);
        $result = html_entity_decode($result, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $result = str_replace("\r\n", "\n", $result);

        // 行番号を付与
        $lines  = explode("\n", $result);
        $pad    = strlen((string) count($lines));
        $output = '';
        foreach ($lines as $i => $line) {
            $lineNo  = str_pad($i + 1, $pad, ' ', STR_PAD_LEFT);
            $output .= "\033[90m{$lineNo}│\033[0m {$line}\n";
        }

        return $output;
    }

    /**
     * ファイルの指定行範囲だけ表示する
     */
    public function displayRange(string $filePath, int $startLine, int $endLine): void
    {
        $lines = file($filePath);
        if ($lines === false) {
            echo "ファイルを読み込めません\n";
            return;
        }

        $total = count($lines);
        $start = max(1, $startLine) - 1;
        $end   = min($total, $endLine) - 1;

        echo "=== " . basename($filePath) . " ({$startLine}〜{$endLine}行) ===\n";
        for ($i = $start; $i <= $end; $i++) {
            $lineNo = str_pad($i + 1, strlen((string) $total), ' ', STR_PAD_LEFT);
            echo "\033[90m{$lineNo}│\033[0m " . rtrim($lines[$i]) . "\n";
        }
    }
}

// CLI での利用例
if (PHP_SAPI === 'cli') {
    $cli = new CliSourceDisplay();
    // $cli->display(__FILE__);
    // $cli->displayRange(__FILE__, 10, 30);
}

⚠️ セキュリティに関する重要な注意事項

show_source() / highlight_file() は非常に便利ですが、公開環境での誤用はソースコード漏洩という深刻なリスクを生みます。

<?php
// ❌ 絶大な危険:ユーザー入力をそのまま渡す
$file = $_GET['file'];
show_source($file);
// → "../../../etc/passwd" や "config/database.php" を指定されたら終わり

// ❌ 危険:認証なしで公開
// URL: https://example.com/view.php?file=../config/database.php
show_source($_GET['file'] ?? '');

// ✅ 安全な使い方の原則
// 1. ユーザー入力を絶対にそのまま渡さない
// 2. 許可リスト(allowlist)で表示できるファイルを限定する
// 3. 認証・認可チェックを必ず行う
// 4. 本番環境では原則使用しない
// 5. IP制限・Basic認証などで保護する

推奨される保護策

対策内容
許可リスト表示できるファイルパスを固定リストで管理する
パス正規化realpath() でパストラバーサルを防ぐ
認証・認可表示前に管理者権限を確認する
環境限定APP_ENV === 'development' のときのみ有効にする
IP制限特定IPアドレスからのアクセスのみ許可する

関連関数との比較

関数対象出力用途
show_source()ファイルハイライトHTMLPHPファイルを色付き表示
highlight_file()ファイルハイライトHTMLshow_source() と同一
highlight_string()文字列ハイライトHTMLPHPコード文字列を色付き表示
php_strip_whitespace()ファイルプレーンテキストホワイトスペース・コメント除去
file_get_contents()ファイル生テキストファイル内容をそのまま取得

よくある落とし穴

<?php
// ❌ NG:戻り値の型を誤解している
// $return=false のとき、成功すると true を返す(HTML文字列ではない)
$result = show_source('file.php');           // 出力あり・true を返す
$html   = show_source('file.php', true);     // 出力なし・HTML文字列を返す

var_dump($result); // bool(true)
var_dump(is_string($html)); // bool(true)
<?php
// ❌ NG:PHPファイル以外に使ってもシンタックスハイライトは機能しない
show_source('style.css');   // CSS は PHP としてパースされるため意味のある表示にならない
show_source('script.js');   // JS も同様

// ✅ PHP ファイルにのみ使用する
show_source('MyClass.php'); // ← PHP コードが正しくハイライトされる
<?php
// ❌ よくある誤解:show_source() 自体が出力バッファリングされると思っている
ob_start();
show_source('file.php'); // ← ob_start() があっても出力される
$content = ob_get_clean(); // 空になる

// ✅ HTML文字列として取得したい場合は $return = true を使う
$html = show_source('file.php', true); // 出力せず文字列で返す

まとめ

項目内容
関数名show_source(string $filename, bool $return = false): string|true|false
別名highlight_file() の完全なエイリアス
主な用途PHPファイルをシンタックスハイライトしてHTMLで出力・取得
$return = trueHTML文字列として返す(出力しない)
セキュリティユーザー入力を直接渡さない・許可リストで限定・認証必須
使用推奨環境開発・学習環境・認証済み管理画面
色のカスタマイズini_set('highlight.*', '#RRGGBB') で変更可能

show_source() は開発・学習・ドキュメント生成の場面で便利な関数です。$return = true で HTML 文字列として取得できるため、独自スタイルへの組み込みや加工も柔軟に行えます。一方、ユーザー入力の直接渡し・公開環境での無制限使用は絶対に避け、許可リストと認証を組み合わせた安全な実装を心がけてください。


参考リンク

タイトルとURLをコピーしました