2011-08-28 60 views
3

我对PHP很陌生,我无法弄清楚为什么会发生这种情况。PHP退出后没有加载页面的其余部分;

由于某种原因,当exit触发整个页面停止加载时,不仅仅是PHP脚本。比如,它会加载页面的上半部分,但是在脚本所在的位置以外没有任何内容。

这里是我的代码:

$page = $_GET["p"] . ".htm"; 
    if (!$_GET["p"]) { 
    echo("<h1>Please click on a page on the left to begin</h1>\n"); 
    // problem here 
    exit; 
    } 
    if ($_POST["page"]) { 
    $handle = fopen("../includes/$page", "w"); 
    fwrite($handle, $_POST["page"]); 
    fclose($handle); 
    echo("<p>Page successfully saved.</p>\n"); 
    // problem here 
    exit; 
    } 
    if (file_exists("../includes/$page")) { 
    $FILE = fopen("../includes/$page", "rt"); 
    while (!feof($FILE)) { 
     $text .= fgets($FILE); 
    } 
    fclose($FILE); 
    } else { 
    echo("<h1>Page &quot;$page&quot; does not exist.</h1>\n"); 
    // echo("<h1>New Page: $page</h1>\n"); 
    // $text = "<p></p>"; 
    // problem here 
    exit; 
    } 
+3

'exit'停止所有页面处理,就在那里。 “死亡”也是如此。无论在何处或何时在代码中,该行之后都不会运行。它等于'完全停止'。 –

回答

9

即使你有HTML代码下面的PHP代码,从Web服务器的角度来看,这是严格意义上的PHP脚本。当调用exit()时,就是它的结束。 PHP将输出进程并输出不再更多的HTML,并且Web服务器不会再输出HTML。换句话说,它的工作原理与预期的一样。

如果您需要终止PHP代码执行流程而不阻止输出任何更多的HTML,则需要相应地重新组织代码。

这里有一个建议。如果有问题,请设置一个表示如此的变量。在随后的if()块中,检查是否遇到以前的问题。

$problem_encountered = FALSE; 

    if (!$_GET["p"]) { 
    echo("<h1>Please click on a page on the left to begin</h1>\n"); 

    // problem here 

    // Set a boolean variable indicating something went wrong 
    $problem_encountered = TRUE; 
    } 

    // In subsequent blocks, check that you haven't had problems so far 
    // Adding preg_match() here to validate that the input is only letters & numbers 
    // to protect against directory traversal. 
    // Never pass user input into file operations, even checking file_exists() 
    // without also whitelisting the input. 
    if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) { 
    $page = $_GET["p"] . ".htm"; 
    $handle = fopen("../includes/$page", "w"); 
    fwrite($handle, $_GET["page"]); 
    fclose($handle); 
    echo("<p>Page successfully saved.</p>\n"); 

    // problem here 
    $problem_encountered = TRUE; 
    } 
    if (!$problem_encountered && file_exists("../includes/$page")) { 
    $FILE = fopen("../includes/$page", "rt"); 
    while (!feof($FILE)) { 
     $text .= fgets($FILE); 
    } 
    fclose($FILE); 
    } else { 
    echo("<h1>Page &quot;$page&quot; does not exist.</h1>\n"); 
    // echo("<h1>New Page: $page</h1>\n"); 
    // $text = "<p></p>"; 
    // problem here 
    $problem_encountered = TRUE; 
    } 

有很多方法可以解决这个问题,其中许多方法都比我提供的例子要好。但是,这是一种非常简单的方式,可以让您无需进行太多重组或风险突破就可以调整现有代码。

+0

你的意思是代码在正在显示的页面上的位置?没有其他方法来阻止PHP而不停止一切? – JacobTheDev

+0

@Rev查看我提供的示例。有很多方法可以跳出你的PHP代码,而不用调用'exit()' –

+0

有很多方法,但代码必须适合这个函数。 'exit'(和'die')应该被认为是专业功能,而不是在继续执行页面时结束输出的方式,因为它不会发生。 –

1

在PHP 5.3+中,您可以使用gotostatement跳转到?>之前的标签,而不是在问题中给出的示例中使用exit

这对于更多结构化代码(跳出功能)来说很难,而且很难。

也许这应该是一个评论,谁知道。

相关问题