I would like to create a function for the common navigation links on my website. I thought I could create a php function and call it but I don’t know how to set it up.
This is what I have:
<div class="left_side">
<ul>
<li><a href="page1.php">First Page</a></li>
<li><a href="page2.php">Second Page</a></li>
<li><a href="page3.php">Third Page</a></li>
</ul>
</div>
<div class="right_side">
<!-- contents of this page -->
</div>
Since the links on the left_side are the same for every page, how do I create a php function so that it can be called from several locations?
Ie. I would like it to look something like:
html:
<?php left_side() ?>
<div class="right_side">
<!-- content of this page -->
</div>
php:
function left_side()
{
echo
<div class="left_side">
echo
<ul>
echo
<li><a href="page1.php">First Page</a></li>
echo
<li><a href="page2.php">Second Page</a></li>
echo
<li><a href="page3.php">Third Page</a></li>
echo
</ul>
echo
</div>
}
Most of the server code is in php. So it would have to look something like this:
<?php
session_start()
require_once("php.php"); // the above php code with the left_side() function
function showPage()
{
include("html.html"); // the above html code
}
?>
Thanks.
Put your function in a file called function.php like this:
Then on each page, do this at the top somewhere:
You can then use it with
Generally, require() is better than include() because you will want it to throw an error if the file is missing (it will break your site not to have the HTML output). Also, require_once() is better than require() because the function only needs to be read one time by the webserver. If you start to include other files e.g. a standard header and footer in your page, which also call function.php, then require_once() will not run on those subsequent pages, leading to a slight performance gain.
Having said that, if you are just outputting HTML, you don’t necessarily need a function wrapper at all. Just use echo statements in function.php (you can also just use HTML without echo) and use include() to have the stuff outputted every time you call it.