停止解析PHP脚本并将其余部分输出为文本?

时间:2017-12-29 13:26:37

标签: php

我有一个PHP脚本,我希望能够显示用户指定if statement GET参数的源代码。

请注意this question不同,其中对象是显示另一个脚本的来源。我想显示当前脚本的源代码,但仅当条件评估为source时,否则脚本应该正常执行。

想要显示脚本的条件检查部分,只显示实际的业务部分

true

因此,如果用户访问http://example.com/myscript.php?source=true,他会在浏览器中显示此内容(作为文字):

<?php
    if( isset($_GET['source']) )
        // Stop executing and display rest of script as text

    // The rest of the script, for example:
    $a = 1;
    $b = 2;
    $c = $a + $b;

3 个答案:

答案 0 :(得分:1)

我会做这样的事情:

<?php

if( isset($_GET['source']) ){
    echo file_get_contents('real_script.php');
} else {
    require_once 'real_script.php';
}

real_script.php将包含要显示的代码:

<?php
$a = 1;
$b = 2;
$c = $a + $b;

但在客户端显示服务器代码存在安全风险,因此我会非常谨慎地使用它。

答案 1 :(得分:-1)

在其他答案的帮助下,我提出了这个解决方案,它运行得非常好,并且不需要多个脚本,配置.htaccess或其他任何内容。

<?php

    if( isset($_GET['source']) ){
        $source = file_get_contents(__FILE__, true);
        highlight_string( '<?php'.mb_substr($source, mb_strrpos($source, '**Source-start**')+16) );
        exit;
    }

    // **Source-start**

    $a = 1;
    $b = 2;
    $c = $a + $b; 

显示为

    $a = 1;
    $b = 2;
    $c = $a + $b; 

语法高亮。

答案 2 :(得分:-3)

highlight_string()是一个选项,在这里我使用了2个单引号来放置代码。如果我们使用<?php?>,我们甚至会获得php代码的颜色。

if(true) // Stop executing and display rest of script as text
highlight_string(
'<?php
    // The rest of the script, for example:
    $a = 1;
    $b = 2;
    $c = $a + $b; 
?>'  );