PHP退出后不加载页面的其余部分;

Jac*_*Dev 3 html 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;
  }
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 9

即使您的PHP代码后面有HTML代码,从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;
  }
Run Code Online (Sandbox Code Playgroud)

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