PHP website template include code

五迷三道 提交于 2019-12-12 06:01:42

问题


I am trying to have this code on my index.php page so that all I have to do is write short files with nothing but html in them to serve as separate pages of the site. For example:

Instead of having the index, about, and contact pages all have the same code for the template, i want to have JUST the index page have the website template, and have a link to about and contact on the main page navigation such as

        <a href="index.php?id=about.html">About</a> 
        <a href="index.php?id=contact.html">Contact</a>

along with a php include code. the trick is I am also using a php news script to display updates and stuff on the main pages so the include for the links will have to be an else statement im guessing?

This is what i've got so far, but its returning errors saying

'id' is an undefined index.

I am not sure what that means.

        <?php 
        $id = $_GET['id']; 
        if 
        ( isset($_GET['id']))
        { $number=5; include("news/newsfilename.php"); }
        else 
        { include "$id"; } 
        ?>

回答1:


First off, a disclaimer about using query strings to modify your home page: it's not at all good for SEO. You'd be much better to use a form of .htaccess magic to create alias subdirectories that pass behind the scenes to your query structure. E.g. /about could be a hidden alias to index.php?id=about.html. Given that you didn't ask this though, I'll keep the how-to out of my answer.

$id = $_GET['id']; is also not going to work for you if the id query parameter isn't set, and though you're checking it, you're also setting the $id variable beforehand.

Try shorthand like this:

<?php 
    $id = isset($_GET['id']) ? $_GET['id'] : 0; //This is equivalent to a long-form if/else -- if $_GET['id'] is set, get the value, otherwise return 0/false
    if ($id)
    { 
        $number=5; include("news/newsfilename.php"); 
    }
    else 
    { 
        include($id.".html"); //also suggesting you strip out .html from your HTML and add it directly to the php.
    } 
?>

And then your html:

<a href="index.php?id=about">About</a> 
<a href="index.php?id=contact">Contact</a>



回答2:


I think this may be the result of your first line of code. Since you are trying to get 'id' before checking to see if it isset, if it is not set you are going to get an error.



来源:https://stackoverflow.com/questions/19603329/php-website-template-include-code

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