I'm currently using include 'header.php'
and include 'footer.php'
in every page, and as far as I know that's how most people do it. I thought of a way that I personally thought would be better, however. I thought of making index.php, then in the index include the page. This would both eliminate the need for a footer and eliminate the need for include
twice in every page. I'm really new to php, however, so I don't know how I would do this. I tried using POST
and GET
methods, but it doesn't seem to work. What I want to achieve开发者_Go百科 is including pages in the header using a URL such as http://mysite.com/index.php?page=history and then load history.php. If I need to clarify something, just ask. Sorry if I don't accept an answer right away, I'm really drowsy. I'll get to it when I can.
It is not a problem if you include 2 pages in a file, like header.php and footer.php... Just writing 2 lines of code in each page is not a matter.
You can decide what pages you want to include dynamically in every page by using if statement, instead of passing the page name in the url.
If you'll do it via index.php, you will no doubt do it wrong.
Nothing bad - every newbie does it this way.
Just because you're thinking of includes, while you should be thinking of templates.
You can make it via index.php, no problem. But there should be not a single HTML tag in this index! As well as in the actual page.
No matter if you're doing it in separate pages or via index.php, the scenario should be the same:
- Get all data necessary to display particular page.
- Call a template.
Thus, your regular page would look like
code
code
code
include 'template.php';
while index.php would look like
get page name
sanitize page name
include page
include 'template.php';
now you can decide what to choose
First off i agree with Meager... Take a look at soem frameworks. Most will use a two step view which essentially does this althoug in a more complex and flexible way.
With that said it would look something like this:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home'; // default to home if no page
if(file_exists($page.'.php')) {
// buffer the output so we can redirect with header() if necessary
ob_start();
include($page.'.php');
$content = ob_get_clean();
}
else
{
// do something for error 404
}
?>
<html>
<head></head>
<body>
<?php echo $content; ?>
</body>
</html>
You could get more complex than that. One thing you want to do uis make sure you dont blindly assume that the page in the $_GET
var is safe... make sure the file exists on your server or otherwise sanitize it...
精彩评论