Reputation: 306
I am trying to output the page title dynamically. I am using induces and this script is withing the header.php the goal is to output the header dynamically using a case/switch statement. here is my code:
<?php $title ;
switch($_SERVER['PHP_SELF']) {
case '/index.php':
$title = 'Home';
break;
case '/about.php':
$title = 'About';
break;
case '/services.php':
$title = 'Services';
break;
case '/portfolio.php':
$title = 'Portfolio';
break;
case '/staff.php':
$title = 'Staff';
break;
case '/contact.php':
$title = 'Contact us';
break;
} ?> <title><?php echo $title ?></title>
I am getting a error telling me my variable $title is not defined?
What i am doing wrong?
Upvotes: 4
Views: 1933
Reputation: 1
though a beginner in php, i sorted this out on my own, and it is very simple and logical, consider title as string and it is initially empty one write on top $title = ""; when including header in home page just after inclusion write the value of title(reassigning value of variable)
Upvotes: 0
Reputation: 769
in $_SERVER global array, $_SERVER[PHP_SELF] contains full path of file like
/project_name/index.php or /project_name/about.php or /project_name/services.php
Here project_name is name of your project.
replace
case '/index.php'
case '/about.php'
case '/services.php'
....
to
case '/project_name/index.php'
case '/project_name/about.php'
case '/project_name/services.php'
.....
& also initialize $title in start of php file.
<?php $title = "";
switch ($_SERVER['PHP_SELF']) {
case '/project_name/index.php':
$title = 'Home';
break;
case '/project_name/about.php':
$title = 'About';
break;
case '/project_name/services.php':
$title = 'Services';
break;
case '/project_name/portfolio.php':
$title = 'Portfolio';
break;
case '/project_name/staff.php':
$title = 'Staff';
break;
case '/project_name/contact.php':
$title = 'Contact us';
break;
}
?>
for testing purposes
print_r($_SERVER);
and check for $_SERVER(PHP_SELF) value.
Upvotes: 1
Reputation: 587
The code looks basically fine though you are missing a "default" block to catch anything that is not caught by any of the "case" statements.
Upvotes: 0
Reputation: 2856
In your first line, you have
<?php $title ;
This $title ;
shouldn't be there.
And, as Kailash Ahirwar already mentioned, it's always a good idea to provide a default value for your $title
:
switch($_SERVER['PHP_SELF']) {
[...]
default:
$title = "Default title goes here";
}
Upvotes: 4