Dynamic title in php - php

I am Trying to get the page title (<title>bla..bla..bla..</title>) to be changable in php with a multi-file layout like so:
Functions.php is included into index.php, then get_header() is called from functions.php to include the page header.php the title tag is inside the header file. I would like to be able to set the title from index.php how can i do this?
For examle this is what i have tried:
Index.php:
<? require_once('includes/functions.php'); global $t; $t = '/home/s0urc3'; get_header();?>
<div id="main">
<h2>NEEDED</h2>
<p class="postmeta">Permalink | <span class="date">Revision Date</span></p>
<p>CONTENT AND CRAP</p>
<!-- main ends -->
</div>
<?php /*test*/echo($title);/*test*/ get_footer();?>
Header.php:
<?php //include('functions.php')?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<? title('$t')?>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<?php get_theme_css()?>
</head>
<body>
<!-- wrap starts here -->
<div id="wrap">
<!--header -->
<div id="header">
<h1 id="logo-text"><img src="<?php get_url('images/Logo.png')?>" alt="S0URC3"><!-- S0URC3 --></h1></div>
<p id="intro">
Just another poorly coded website!
</p>
</div>
<div id="nav">
<!-- <div id="navi"><div id="menu" class="fixed"> -->
<ul class="">
<li class="">Home</li>
<li class="">Blog</li>
<li class="">Forums</li>
<li class=""> Comments</li>
<!--<li class="">Clans</li>-->
<li class="">-astro-</li>
<!--<li class="">Inspiration</li>
<li class="">Resources</li>
<li class="">Tutorials</li>
<li class="">WordPress</li>-->
</ul><!-- </div></div> -->
</div>
<!--header ends-->
</div>
<!-- content-wrap starts -->
<div id="content-wrap">
Functions.php:
<?php
require_once('constants.php');
//===============//
//Start Functions//
//===============//
//Gets a file from the domain http://files01.s0urc3.ismywebsite.com/
function get_url($file)
{
echo (FILE_ROOT . $file);
}
//gets the url of the theme
function get_theme_css() {echo('<link rel="stylesheet" href="' . FILE_ROOT . 'colourise/style.css" type="text/css" />');}
function get_header() {require_once('includes/header.php');}
function get_footer() {require_once('includes/footer.php');}
//Gets the URL of the current page
function page_url($p)
{
$s = empty($_SERVER["HTTPS"]) ? ''
: ($_SERVER["HTTPS"] == "on") ? "s"
: "";
$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
: (":".$_SERVER["SERVER_PORT"]);
if ($p == 'yes')
echo ($protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']);
else
return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2)
{
return substr($s1, 0, strpos($s1, $s2));
}
//gets the year
function cur_year() {echo (YEAR);}
function ads($code) {echo('<script type="text/javascript" src="http://links.ismywebsite.com?i='. $code .'"></script>');}
function title($title)
{echo('<title>Index Of: '.$title.'</title>');}
//=============//
//End Functions//
//=============//
?>
P.S. I only am including functions once all functions are available in the header and footer when functions.php is called in index.php

First, the file header.php is being included from within a function, so it does not have access to the global variable $t. You will need to do one of the following:
In functions.php:
function get_header() {
global $t;
require_once('includes/header.php');
}
Or, in header.php:
<?php //include('functions.php')
global $t;
?>
<!DOCTYPE html>
<!-- etc -->
That way, the variable you have declared will be available to the function's local variable scope.
Second, you need to call the function with either double quotes or no quotes at all. Single quotes will not parse a variable.
Right
title($t);
title("$t");
title("{$t}");
Wrong
title('$t');
Here is the PHP Manual Page on the String datatype -- be sure to check out single quoted strings versus double quoted strings.
Nitpicky Things:
You should always use the full opening tags (<?php), and not the short open tags (<?)
Your functions, like title(), should always return a value, and you can echo that, rather than echoing directly from inside the function.
The strleft() function you implemented, though clever, already exists. See: strstr() Actually, this function does the opposite of what you want; I mis-remembered what it did. Carry On. EDIT AGAIN: No, apparently I was right, you pass the optional third parameter as true. You should generally use functions that already exist because, with certain exceptions, they will be faster.
A Notable exception to this rule is array_rand()

Try to change
<? title('$t')?>
to
<? title($t)?>
in your code.

Related

PHP echoing in wrong location of html

I'm attempting to make a template based system to deliver content but I've run into a problem that I just can't seem to solve. When I try to echo out variables that have data from includes it gets outputted in the wrong section of my html.
Below is 'newstuff.php' which is my page to be executed on the browser, the offending variables are $php $head $content.
<?php
$php = include "templates/content/newstuff/phpCode.php";
$head = include "templates/content/newstuff/head.html";
$content = include "templates/content/newstuff/content.php";
include realpath(dirname(__FILE__)).'/templates/templateMain.php';
?>
Below is 'tempalteMain.php' this is my tempalte. Note the location of the echoing of $php $head $content.
<?php
echo $php;
?>
<!DOCTYPE html>
<html>
<head>
<?php echo $head; ?>
</head>
<body class="body1" onload="inputBlur2()">
<div class="borderLine"></div>
<div class="banner"></div>
<div class="mainContent1" >
<div class="header1" >
<div class="headerContainer" >
<ul class="navList1">
<li><a id = "B0" href="index.php">New Stuff</a></li>
<li><a id = "B1" href="MainPage.php">Products</a></li>
<li><a id = "B2" href="ProjectsPage.php">Projects</a></li>
<li><a id = "B3" href="AOrdering.php">About Ordering</a></li>
<li><a id = "B4" href="ContactMe.php">Contact Us</a></li>
<li><a id = "B5" href="FAQPage.php">FAQ</a></li>
<li><a id = "B6" href="SCart.php">My Cart</a></li>
</ul>
</div>
</div>
<div class="content1">
<?php echo $content; ?>
</div>
</div>
</body>
</html>
Below is 'head.html' this provides the code to be delivered by the $head PHP variable.
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/../StylePR.css">
<title>KickUp Electronics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
Below is 'content.php' this provides the code to be delivered by the $content PHP variable.
<p>Welcome to the new stuff page!!!</p>
Finally, this is the page source that gets outputted taken from the chrome DOM editor. Note the locations of the information from content.php are wrong and there are strange '1's that are echoed out (also, when viewing the page source, the information from head.html is placed outside the html tags).
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/../StylePR.css">
<title>KickUp Electronics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body class="body1" onload="inputBlur2()">
<p>Welcome to the new stuff page!!!</p> <!--Wrong Location!-->
1
1
<div class="borderLine"></div>
<div class="banner"></div>
<div class="mainContent1">
<div class="header1">
<div class="headerContainer">
<ul class="navList1">
<li><a id="B0" href="index.php">New Stuff</a></li>
<li><a id="B1" href="MainPage.php">Products</a></li>
<li><a id="B2" href="ProjectsPage.php">Projects</a></li>
<li><a id="B3" href="AOrdering.php">About Ordering</a></li>
<li><a id="B4" href="ContactMe.php">Contact Us</a></li>
<li><a id="B5" href="FAQPage.php">FAQ</a></li>
<li><a id="B6" href="SCart.php">My Cart</a></li>
</ul>
</div>
</div>
<div class="content1">
1 </div>
</div>
</body></html>
I tried searching many times for a solution to no avail. Is this a problem with the echo being executed before the html fully loads? Any help would be highly appreciated!
You're using includes wrong.
$php = include "templates/content/newstuff/phpCode.php";
is immediately outputting the output of that file, and setting $php to 1 (i.e. "it worked!").
Handling Returns: include returns FALSE on failure and raises a warning. Successful includes, unless overridden by the included file, return 1. - http://php.net/manual/en/function.include.php
You can use output buffering to capture the output, but a better solution is probably moving the include calls directly into templateMain.php.

Passing Variable to other PHP without refreshing

I am new to PHP. I have these 3 files :
index.php
functions.php (to organize functions)
header.php
I want to simplify(which has been done so far) the index.php page thus I do not need to write the and all stuff again and again. So I created header.php that can be loaded by index.php:
header.php
<!Doctype html>
<html lang="en">
<head>
<title>Learn PHP</title> <!--This is the problem, every page that loads header.php will have same title! -->
</head>
<body>
<div class="header">
<h1>Learn PHP</h1>
<p>Your library of PHP learning!</p>
<hr/>
</div>
<!-- footer is handled by footer.php that include </body> and </html>-->
I have even simplified things further by making a function in functions.php so that I can just type "get_header()" in the index.php without writing the whole code again.
functions.php
<?php
function get_header(){
if (file_exists('header.php')){
require 'header.php';
}
else{
echo "There is an error retrieving a file";
}
}
?>
Now, how do I allow this index.php to have custom page title instead of the default given by header.php?
Am I missing something important. I have tried creating a variable and try to pass it to the functions.php, but it didn't work. Or is there any cleaner way to do this?
I am inspired by how wordpress organize their files, I have checked the wordpress file. And then I decided to try something from scratch so I understand better and improve my PHP skills.
I know can use POST and GET, but no I dont want to refresh or load a new page just to change a page title especially index.php
EDIT :
Here I included my index.php
<?php
require 'functions.php';
?>
<?php
get_header();
?>
<table>
<h3>What we learned</h3>
<ul>
<li>Syntax </li>
<li>Variables </li>
<li>Code Flow </li>
<li>Arrays </li>
<li>Superglobals </li>
</ul>
</table>
<?php get_footer(); ?>
It seems like all you need you want is simple includes. You're actually making it harder by using a function, here, because an include has the same scope as where it was included from. E.g.
header.inc
…
<title><?php echo isset($title) ? $title : 'Untitled';?></title>
…
index.php
<?php
$title = 'Welcome';
require 'header.inc';
?>
welcome
another-page.php
<?php
$title = '2nd page';
require 'header.inc';
?>
2nd page content
If you want to use a function, give it parameters.
function get_header($title = 'Some default title') {
…
}
the included file will have access to the variables in the function's scope.
in the functions.php
function get_header(){
if (file_exists('header.php'))
require 'header.php';
else echo "There is an error retrieving a file";
}
in the header.php, and in the balise title you call the session parameter
<!Doctype html>
<html lang="en">
<head>
<title>
<?php if(!empty($_SESSION['title-page'])) echo $_SESSION['title-page']; else 'Learn PHP'; ?>
</title>
</head>
<body>
<div class="header">
<h1>Learn PHP</h1>
<p>Your library of PHP learning!</p>
<hr/>
</div>
<!-- footer is handled by footer.php that include </body> and </html>-->
and in the index.php
<?php
session_start();
$_SESSION['title-page'] = 'this is the welcome Page';
require 'functions.php';
get_header();
?>
<table>
<h3>What we learned</h3>
<ul>
<li>Syntax </li>
<li>Variables </li>
<li>Code Flow </li>
<li>Arrays </li>
<li>Superglobals </li>
</ul>
</table>
<?php get_footer(); ?>
and in another-page.php
<?php
session_start();
$_SESSION['title-page'] = 'this is an another Page';
require 'functions.php';
get_header();
?>
<table>
<h3>What we learned</h3>
<ul>
<li>Syntax </li>
<li>Variables </li>
<li>Code Flow </li>
<li>Arrays </li>
<li>Superglobals </li>
</ul>
</table>
<?php get_footer(); ?>

How To Properly Structure php Navigation Bar

I have a index file in my root directory.
I have a directory called pages.
Nav bar is in the includes directory.
If I want to include the navbar in index.php and also in each one of my pages.php which are located in the pages directory. What is the proper way to structure this nav bar so the php can move up and down directories by what page it is on.
each page is identified as
$page = currentPage
And here is my current navbar which is in the includes dir
<ul>
<?php if ($page == 'home') { ?><li class="active">Home</li>
<?php } else { ?><li>Home<?php } ?>
<?php if ($page == 'contact') { ?><li class="active">Contact Us</li>
<?php } else { ?><li>Contact Us<?php } ?>
<?php if ($page == 'services') { ?><li class="active">Services</li>
<?php } else { ?><li>Services<?php } ?>
<?php if ($page == 'employees') { ?><li class="active">Employees</li>
<?php } else { ?><li>Employees<?php } ?>
<?php if ($page == 'dashboard') { ?><li class="active">Dashboard</li>
<?php } else { ?><li>Dashboard<?php } ?>
</ul>
Directory looks like this.
root
root/includes
root/pages
Thanks for your help in advance. I realize I could just do some simple things to get around this but I really want to understand this for the future.
This is how the page is currently laid out:
<?php $page = 'contact'; ?>
<html>
<meta charset="utf-8">
<title>Contact Us</title>
<head>
<base href="http://www.mysite.com/Dir_IM_Working_on_root/pages/" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
</head>
<body>
<div id="wrapper">
<div id="nav">
<?php include '../includes/nav.php'; ?>
</div><!-- CLOSING NAV DIV -->
<div id="main">
</div><!-- CLOSING MAIN DIV -->
<footer>
<?php include '../includes/footer.php'; ?>
</footer>
</div><!-- CLOSING WRAPPER DIV -->
</body>
</html>
Easiest would be to output absolute URLs in all cases. (/test.php)
If you want to leave the possibility to run your site in a subfolder, you can prepend all paths with a variable. This can be changed to the current position of your site.
Another way is to add a
<base href="http://www.example.org/subfolder/" />
to your html code and change that accordingly in combination with absolute URLs. All URLs are based on what you put into the attribute. This is a very elegant solution, but it affects a lot, which might be surprising if one is not that trained in web linkage.
I think there is no "right" way. Typo3 uses the base tag variant and it's most likely the way I would use. Lots of other software use the variable variant (or wrap the path in a function -- which is just another way of achieving the same). Just try some ways and decide for the one which seems most appealing to you I'd say.
In my experience the only thing nearly nobody uses are relative URLs.
Update
Use this html in combination with base html tag.
<ul>
<li<?php if ($page == 'home') echo ' class="active' ?>>Home</li>
<li<?php if ($page == 'contact') echo ' class="active' ?>>Contact Us</li>
<li<?php if ($page == 'services') echo ' class="active' ?>>Services</li>
<li<?php if ($page == 'employees') echo ' class="active' ?>>Employees</li>
<li<?php if ($page == 'dashboard') echo ' class="active' ?>>Dashboard</li>
</ul>

php template for different pages with different css and mysql

Hi I'm trying to figure out how to do a PHP template system with a class, i dont like header.php footer.php or smarty or whatever blabla, just want the template.html, the class.php and page1.php, page2.php etc... with my own php code, and I've found a lot of website of people teaching how to do this but i still have lots of questions.
1) i want to add EXTRA css to some pages
2) SOME pages has php code like mysql queries and stuff like that
3) the CONTENT which would be a variable where ever i want in the template is not only words, instead is a large amount of divs and stuff, also in some pages the CONTENT variable has queries inside, like fillin a (e.g)dropdown menu.
Hope somebody can guide me in this, i actually have my tempalte for explame, (the tags are just random)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<title>CompanyName | ##TITLE##</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<link href="styles.css" rel="stylesheet" type="text/css" />
##EXTRA_CSS##
<link rel="shortcut icon" href="/favicon.ico" />
<!--[if IE 6]>
<script src="DD_belatedPNG_0.0.8a-min.js"></script>
<script>
DD_belatedPNG.fix('img, div');
</script>
<![endif]-->
##EXTA_JS##
</head>
<body>
<div id="main">
<div id="container_black">
<div id="container_white">
<div id="container_header">
<div id="logo_top"></div>
<div id="lineas_verticales_top">
<div class="volver_portada">Volver a portada</div>
<div class="english_spanish"><u>Español</u> | English</div>
</div>
<div id="nav_bar_black"><div id="nav_bar_red"><div id="nav_bar_yel">
<ul class="menuholder">
<li class="menu_principal">Principal</li>
<li class="menu_empresa">Empresa</li>
<li class="menu_productos">Productos</li>
<li class="menu_clientes">Clientes</li>
<li class="menu_recetas">Recetas</li>
<li class="menu_contacto">Contacto</li>
</ul>
</div></div></div>
<div id="topbg_degr"></div>
</div>
<div id="container_left">
<div id="conmargen_left_top"></div>
<div id="container_conmargen_left_middle">
##CONTENT##
</div>
<div id="conmargen_left_bottom"></div>
<!--[IF INDEX]
<div id="fono"></div>
<div id="dir"></div>
-->
</div>
<!--[IF INDEX]
<div id="nav"></div>
-->
<div id="container_right">
<div id="conmargen_right_top"></div>
<div id="container_conmargen_right_middle">
<!--[IF PAGE OR PAGE OR PAGE]
[ELSE IF]
[ELSE IF]
-->
</div>
<div id="conmargen_right_bottom"></div>
</div>
<!--[IF INDEX]
<div id="frame_facebook">
<span>CompanyName</span> en Facebook
<div class="breakL"></div>
<fb:like href="#" layout="button_count" show_faces="true" width="100" font="tahoma"></fb:like>
</div>
-->
<br/>
</div> <!-- cierre del container white -->
</div> <!-- cierre del container black -->
<div id="footer">
<div class="footer_comment">
CompanyName Todos los derechos reservados 2011
</div>
</div>
</div> <!-- cierre del main -->
<br/>
</body>
</html>
for instance contact.php, the content would be a form, and on the top of the page i have this huge php code, where i validate and all.
I'd really appreciate if somebody would put me in the right path to do this. thank you in advance.
There are probably a hundred different ways you could approach this, each with their own advantages and disadvantages - using databases and/or ajax calls and/or headers and footers as you already said. You really have to work out which way works best for your particular project or style of coding, or both.
However - if you really just want 'template.html', but have some pages with PHP, javascript, MySQL or whatever else in them - then I would suggest.
Create template.html with placeholders such as {PAGE_TITLE}, {MAIN_CONTENT} or whatever you need.
Create page1.php/page2.php etc and do any server side work, generate variables to match your placeholders. It might be handy to store them as an array, ie:
PAGE_VARS array(
['TITLE'] => My Page
['CONTENT'] => This is my page content
)
At the end of your 'page' script, load the entire contents of template.html into a string
$template = file_get_contents('template.html')
Then, build up your template with the replaced variables using either a basic loop:
foreach ($PAGE_VARS as $KEY=>$VALUE) {
$template = str_replace("{".$KEY."}",$VALUE,$template)
}
(Feel free to get clever and probably more efficient with some regular expressions above, this is just a quick example.)
Output your template.
echo $template;
You can create a quick class (class.php) like this that will be your 'template engine' :
class Template {
var $contents;
function load($file) {
if ($fp = fopen($file, "r")) {
$this->contents = fread($fp, filesize($file));
fclose($fp);
}
}
function replace($str,$var) {
$this->contents = str_replace("<".$str.">",$var,$this->contents);
}
function show() {
$search = array(
'/\t/', //Remove Tabs
'/<!--[^\[-]+?-->/', //Remove Comments
'/\n\n/' //Remove empty lines
);
$replace = array(
'',
'',
''
);
$this->contents = preg_replace($search, $replace, $this->contents);
echo $this->contents;
}
}
In your template.html file, add special tags where you want to put your content, like this :
<html><head></head>
<body>
<div id="id1"><page_title></div>
</body>
</html>
...
Then create a function to write inside the tags (one per zone) :
function writetitle($s) {
$GLOBALS['writes']++;
$GLOBALS['page_title'] .= $s;
return;
}
finally, in your page.php, call the class, write your content, and generate the page :
require_once('class.php');
//Load Class
$template = new Template;
$template->load("template.html");
//Some query :
$query = mysql_query('SELECT...');
$res = mysql_num_rows($query);
//write your content :
writetitle('my title, '.$res.'');
//Generate the page :
$template->show();
Doing this you can create as many zones as you want. writetitle act like echo, so you can make queries and everything you want.
I hope it helps.
Insetad of having PHP parsing your template files I would suggest writing the templates using PHP and not your own pseudo code.
It's perfectly valid to write
...
<body>
<?php if($fooBar == "hahahaha"):?>
The cool foobar link
<?php endif;?>
</body>
...
I would then create a layout file with all common html etc. Then using small template snippets to be inserted into the layout where the main content goes.
By having actual PHP code in your templates the PHP enginge can handle them and you don't have to write your own logic to handle loops, if statements etc.
Take a look at Zend Framework and you'll get a good idea of how you can write your template engine.

Changing element ID with javascript

I am loading in the following navbar html from a required PHP file:
<ul id="navlist">
<li id="active">Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
Depending on the page that I am on (let's say I am on the alumni.php page) I want that list item to be given the ID "active"?
Edit: Here is my header.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles/main.css" type="text/css" media="screen" charset="utf-8"/>
<link rel="stylesheet" href="styles/navbar.css" type="text/css" media="screen" charset="utf-8"/>
<title>some title</title>
</head>
<body>
<div id="header">
<div id="left">
<img src="images/tree.png" alt="tree" width="87" height="98"></img>
</div>
<div id="right">
<
</div>
</div>
<div id="navigation">
<ul id="navlist">
<li>Home</li>
<li>About</li>
<li>News</li>
<li>Applying</li>
<li>Current <br />Residents</li>
<li>Alumni</li>
<li>Contact</li>
</ul>
</div>
I assume that I need to do this through Javascript once the page loads? How would I do this?
as said in comment, PHP will be a better way.
You can simple doing it like this :
<?php
$header = file_get_content('header.html');
$page = 'about.php';
$header = str_replace('<li><a href="'.$page.'">', '<li id="active"><a href="#">', $header);
You should assign the ID (which should be a class, semantically speaking, IMHO) using PHP whilst generating the page. Using JS is not only troublesome (you have to go and check your location, probably match a regexp, etc), but also inelegant.
I'd say that in common coding for javascript where you want a particular element to be 'active' or 'highlighted' or 'enabled', make use of the class attribute. Your id attribute implies a static attribute of the data being used.
I think this will do what you want.
<ul id="navlist">
<li id="home">
Home
</li>
<li id="about">
About
</li>
<li id="news">
News
</li>
<li id="applying">
Applying
</li>
<li id="currentResidents">
Current Residents
</li>
<li id="alumni">
Alumni
</li>
<li id="contact">
Contact
</li>
</ul>
<script type="text/javascript">
var pagePath = window.location.pathname;
var pageName = pagePath.substring(pagePath.lastIndexOf('/') + 1);
var currentActive;
function setActivePage(page)
{
if(currentActive)
document.getElementById(currentActive).removeAttribute("class");
document.getElementById(page).setAttribute("class", "active");
currentActive = page;
}
if(pageName == "about.html")
setActivePage("about");
else if(pageName == "otherpage.html")
setActivePage("otherpage");
// Etc...
</script>
If you were using jQuery this may have been done in a better and lesscode way... but I assume you're not using it.
Hope it helps :)
While it may be possible (I haven't actually tried it), you would not typically change the id of an element in the page. Instead, it would be a better approach to use class="active" instead of id="active".
Also, you probably want to generate the appropriate html for it on the server-side, as you're building the rest of the page. Something like this would work (though there are many different ways to build this code, depending on your server's implementation):
<ul id="navlist">
<li class="<?php echo (($currentPage=='Home')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='About')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='News')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='Applying')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='Residents')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='Alumni')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='Contact')?'active':''); ?>">Contact</li>
</ul>
Note: I've also removed the id="current" attribute from the anchor (<a ...>), because I'm assuming that this would change depending on the current page as well, and it's unnecessary, because you can build CSS selectors to address the anchor, without giving it its own special id or class.
Here's what your CSS might look like:
#navlist li.active {
/* css rules for the active LI */
}
#navlist li.active a {
/* css rules for the active (a.k.a. "current") anchor inside the active LI */
}
hope this helps.
[edit] As I said above, it all depends on the architecture of your php code. But assuming that you have a bunch of php pages (eg: "Home.php", "About.php", "News.php", etc.); and each of those pages includes your nav code using something like: require("nav.php");. Then you can just do the following in each of your main php files:
<?php
/* $currentPage, declared here, will be available to php code inside nav.php */
$currentPage = strtolower(basename(__FILE__));
require("nav.php");
?>
Just be sure that you set $currentPage, in each page's main script, somewhere prior to including your nav code (ie. before you call require(...)). The nav code will then be able to "see" $currentPage and use it.
So, for example, if the above code is executed in a file called "About.php", then $currentPage will be set to "about.php" (filename gets converted to all lowercase by the call to strtolower(...)). Then, when "nav.php" gets included, it will be able to access $currentPage and "see" that we're on the 'about' page.
You can change my example above, as follows, to use values of $currentPage that were generated from the filename using the approach I've described here.
<ul id="navlist">
<li class="<?php echo (($currentPage=='home.php')?'active':''); ?>">Home</li>
<li class="<?php echo (($currentPage=='about.php')?'active':''); ?>">About</li>
<li class="<?php echo (($currentPage=='news.php')?'active':''); ?>">News</li>
<li class="<?php echo (($currentPage=='applying.php')?'active':''); ?>">Applying</li>
<li class="<?php echo (($currentPage=='residents.php')?'active':''); ?>">Current <br />Residents</li>
<li class="<?php echo (($currentPage=='alumni.php')?'active':''); ?>">Alumni</li>
<li class="<?php echo (($currentPage=='contact.php')?'active':''); ?>">Contact</li>
</ul>

Categories