2011-08-28 59 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

這對於更多結構化代碼(跳出功能)來說很難,而且很難。

也許這應該是一個評論,誰知道。

相關問題