How do I use PHP to display one html page or another?

旧街凉风 提交于 2020-05-09 06:17:23

问题


I wanted to use PHP and the if statement, and I wanted to do

if ($variable){
display html page1
}
else {
display html page2
}

How do I do this? An please note, that I do not want to redirect the user to a different page.

--EDIT-- I would have no problem doing that with one of them, but the other file, it would be too much of a hassle to do that.

--EDIT-- Here is the coding so far:

<?PHP
include 'uc.php';
if ($UCdisplay) {
    include("under_construction.php");
}
else {
    include("index.html");
}
?>

My problem is that it would be really complicated and confusing if I were to have to create an html page for every php page, so I need some way to show the full html page instead of using include("index.html")


回答1:


if ($variable){
  include("file1.html");
}
else {
  include("file2.html");
}



回答2:


The easiest way would be to have your HTML in two separate files and use include():

if ($variable) {
    include('page1.html');
}
else {
    include('page2.html');
}



回答3:


using the ternary operator:

 include(($variable ? 'page1' : 'page2').'.html');



回答4:


If you want to avoid creating "an html page for every php page", then you could do something like this, with the "real" content directly inside the PHP page.

<?PHP
include 'uc.php';
if ($UCdisplay) {
    include("under_construction.php");
    exit;
}
?>
<html>

<!-- Your real content goes here -->

</html>

The idea is this: If $UCdisplay is true, then your under construction page is shown, and execution stops at exit; - nothing else is shown. Otherwise, program flow "falls through" and the rest of the page is output. You'll have one PHP file for each page of content.

You could side-step this issue by moving the code that checks $UCdisplay directly into uc.php; this would prevent you from having to write that same if statement at the top of every file. The trick is to have the code exit after you include the construction page.




回答5:


For those still looking: See the readfile(); function in php. It reads and prints a file all in one function.

Definition

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

Reads a file and writes it to the output buffer.



来源:https://stackoverflow.com/questions/2126624/how-do-i-use-php-to-display-one-html-page-or-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!