Currently my site title looks like:
<title>My Site Title</title>
The above code is added on 'header.php' file, so every pages has the same page title.
I need to set different titles for different pages.
for example,
<title>
if 'contact.php' then title= 'Contact Us'
else if 'faq.php' then title= 'FAQ'
else if 'add.php' then title= 'Add'
else title= 'My Site Title'
</title>
somebody please help me!!
I guess contact.php include 'header.php';. Then something like this would work:
contact.php:
<?php
$title = 'Contact Us';
include 'header.php';
// your code
?>
header.php:
<?php
echo '<title>'.$title.'</title>';
Tip: have a look at template engines. I like smarty for example. Maybe someone will comment on this with some other examples ;)
Make a variable in your script called $page and use that variable in the template file.
Business logic for page Home, for example:
<?php
.
.
.
$page = 'Home';
render($page);
View logic page for Home:
.
.
.
<title>
<?php echo $page; ?>
</title>
.
.
.
This is just a concept, it is not a fully functional code.
Split your header in to 2 seperate php files, one before the title, and one after the title (this will work with other page specific data, see note at end of answer)
then the top of your pages should look like:
<?php include_once("inc/begin-head.inc");?>
<title>My Title</title>
<meta name="description" content="description"></meta>
<?php include_once("inc/end-head.inc");?>
There are some other solutions, such as make header a class and define variations to it, and then call a function to output the head completly
Please note, there are a LOT of other paged specific tags. Title, Meta Description, Canonical url link, meta keywords, open graph data .....
You can try like this and use basename($_SERVER['PHP_SELF']) and now lookup for the $title[key]
$title = array();
$title['home.php'] = 'My home page';
$title['Hello.php'] = 'My title';
I'd advice you to use an array with titles instead of a series of ifs (respectively a switch)
<?php
$file = basename($_SERVER['PHP_SELF']);
$titles = array(
'contact.php' => 'Contact Us',
'faq.php' => 'FAQ',
'add.php' => 'Add',
);
if(array_key_exists($file, $titles){
echo '<title>'.$titles[$file].'</title>';
}else{
echo '<title>Ny Site Title</title>';
}
?>
To add title dynamically , first set the following code in header.php file :
<title>
<?php
if(isset($title) && !empty($title)) {
echo $title;
} else {
echo "Default title tag";
}
?>
</title>
and set title in each page before including header as :
$title = "Your Title";
include 'header.php';
How I did this for anyone curious in the future...
I have a "pagetitles.php" page that contains this code:
$page_files=array(
"admin"=>"Admin Panel",
"profile"=>"Your Profile",
"billing"=>"Billing / Subscriptions",
"pricing"=>"Our Pricing",
"settings"=>"Your Settings",
"bugs"=>"Bug/Feature Tracker",
"search"=>"Search Results",
"clients"=>"My Clients");
if(isset($_GET['rq'])){
if(in_array($_GET['rq'],array_keys($page_files))) {
$pagetitle = $page_files[$_GET['rq']];
}
}
Then I include that file at the very top of my index.php page, and echo $pagetitle where I want the title to be. BUT this also requires another file to handle serving the specific pages, using a ?rq request
In my "page_dir.php" file, I have the following that handles ?rq= pages (ex: www.example.com?rq=home will load the home page, with the above page title that's inside of "home" array)
Here's the page_dir.php file:
$page_files=array(
"noaccess"=>"pages/noaccess.php",
"home"=>"pages/dashboard/home.php",
"lists"=>"pages/dashboard/lists.php"
);
if(isset($_GET['rq'])){
if(in_array($_GET['rq'],array_keys($page_files))) {
include $page_files[$_GET['rq']];
}else{
include $page_files['home'];
}}else{
include $page_files['home'];
}
This page_dir.php file, I put on the index page where I want main content to show up at... I then have each individual page with just the content (like home.php file is just home.php content without the navbar and footer)
On my index.php file, where I want the page title, I have this code:
if(isset($code_nav_title)){
echo $code_nav_title;
}elseif(isset($pagetitle)){
echo $pagetitle;
}else{
echo "Default Page Title Here";
}
the $code_nav_title lets me set the page title from form submissions if I want it to say "success" or "failed" :) the "default page title here" lets you set something to automatically show up if everything fails to show (like if you forgot to set the page title)
Hopefully this makes sense! It's saved me sooo many headaches and makes it easy for expansion/changes!
Related
I have a html project, with various template files. I want to display breadcrumbs, in all pages except on index.php and contact.php.
I have the breadcrumbs working; what I can't get it to work is the condition for only displaying it if the pages are not index.php or contact.php:
So far, I know I could do this if it was in the other way around, only display it on those pages:
$noBreadcrumbs = array("index.php", "contact.php");
foreach ($noBreadcrumbs as $page => $pageName) {
if (stripos(filter_input(INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_STRING), $pageName)){
echo '<div class="breadcrumbs container">';
require ("breadcrumbs.php");
echo '</div>';
}
}
But because it has to be in the other way around.... I don't know how to do it! If I echo de request uri it appears also with the project name (thousand_motors/index.php), and.... I am stuck. I can't print only "index.php" and even if so, I don't know how can I do the foreach but when they are not those pages...
Any suggestions?
Thank you
have you tried
if (!stripos( //....
I'm trying to echo out dynamic php titles depends on page for seo purposes.
I successfully did this the pages I call from database depends on their id's.
Like that:
if (isset($_GET["category_id"])) {
$query = $handler->query("SELECT * FROM categories WHERE category_id = ".$_GET['category_id']." ");
while($r = $query->fetch()) {
$title = $r["title"];
}
}
And this is how I echo out:
<title><?php if (isset($_GET["category_id"])) { echo $title; echo " |"; } ?> mypage.com</title>
result:
on category.php?category_id=1 Page title is: "Category 1 | mypage.com"
*
But there are pages which is not static.
for example: index.php, login.php.
*
I want to figure out how to edit my code below to print "Login" on login.php between title tags.
<title>
<?php
if (isset($_GET["category_id"])) {
echo $title; echo " |";
}
?> mypage.com
</title>
EDIT
my login.php is like that:
include("header.php");
content.
So I need to define $title for login.php in header.php
I need to add some codes to header.php when user will see different title on login.php, index.php etc.
I'm able to do it category.php?category?id=1 already with the code above, but I need to also make it for login.php, index.php and so on.
There are several ways to do this within the code you outlined.
First, I'm going to simplify some of your code a bit. This also potentially makes it slightly faster:
echo "<title>$title | mypage.com</title>";
This assumes that $title is going to be set, either by the query from when $_GET['category_id'] is set, or from the file that calls it. The great thing about includes is that they can pass variables. So in the login.php and any other file where you are not doing a GET, just specify $title in that file.
Login.php:
$title = 'Login';
include("header.php");
content.
Which would display page title of "Login | mypage.com".
Okay, I suck at titling my questions XD If anyone has a better title, please edit!
Anyway, I have this in my php.ini file:
auto_prepend_file = ./include/startup.php
auto_append_file = ./include/shutdown.php
startup.php looks something like this:
<?php
chdir(__DIR__."/..");
require("include/db.php");
// more setup stuff here
if( $_SERVER['REQUEST_METHOD'] == "AJAX") { // yup, custom HTTP method :p
// parse file_get_contents("php://input")
}
else {
$output_footer = true;
require("include/header.php");
}
shutdown.php goes something like this:
<?php
if( isset($output_footer)) require("include/footer.php");
Now, on to the main problem.
header.php includes the line <title>My shiny new site</title>. I want that title to depend on the page that is currently being viewed. At the moment, I have some ugly hack that involves JavaScript:
document.title = document.getElementsByTagName('h1')[0].textContent;
Obviously, this is not ideal! Any suggestions on how to adjust the title when said title is being output as a result of an auto_prepend_file?
I don't think you should use the append and prepend functionality like that But that's just my opinion.
Why not create header.php to allow for a variable title text. And drop the prepend and append scripts completely
<title><?php echo (isset($title)) ? $title : 'default title'; ?></title>
And whenever you need a title tag.
$title = "some title";
require("include/header.php");
I'm trying to build a personal website, (fairly new to HTML and PHP) and am having trouble building a dynamic menu bar. By dynamic, I mean that I want the page that the use is on be highlighted.
Right now I have a horizontal menu on my page (Home, Contact, etc...), and have the CSS set up so that when one of the links has the attribute class="active", then the item remains highlighted (so the user knows which page he or she is on).
For example, in a static HTML page I would copy and paste the following code to each other static page and just change where the class="active" attribute is to align with the proper page:
Home
Page Two
Contact
I obviously want to use PHP to be able to minimize the amount of duplicated code I have scattered around.
So far, I have followed the first answer on this page It has worked great. I am able to click on a menu item and the content comes up in the body of the page. However:
I can't get it to dynamically highlight the menu since the menu options (the <a href /> lines) are not being dynamically created through PHP.
When I go to the page directly through index.php, I get an error:
Notice: Undefined index: 'page' in C:\xampp\htdocs\index.php on line 43
Obviously, when I go the page directly, the ?page=home variable is not set in the line:
Home
So, the 'page' variable in GET has not been set. I've gotten around that with an if statement that checks if it is not set and sends the home page html. However, I don't think this is the best way to do it, and when I try to tackle part b), I'm thinking I need to change this completely. My entire PHP script is like this:
<?php
$current_page = 'home';
$pages = array('home', 'pagetwo', 'contact');
function setActiveHeader() {
global $current_page;
global $pages;
$arr_length = count($pages);
for($x=0;$x<$arr_length;$x++) {
if($pages[$x] == $current_page) {
echo "$pages[$x]";
} else {
echo "$pages[$x]";
}
}
}
function putPage($page) {
// put a list of allowed pages here
global $pages;
$page = trim($page);
$page = (in_array($page, $pages)) ? $page : 'home';
// set current page global variable
$GLOBALS['current_page'] = $page;
// output contents of page selected
echo #file_get_contents('.\html\\' . $page . '.html');
}
?>
I just try to call setActiveHeader() from the HTML, but that doesn't work right. The menu is output correctly, but the the correct item doesn't get highlighted, it just stays stuck on the home option highlighted. Not sure why it is not being updated. Is there a better way to go about doing this?
Your code only goes up to 37 lines, and we can't much without the line that the error is referencing, but I'll try my best.
Basically, what Undefined Index means, is that you're trying to access an element in an array that isn't set. I'm guessing that you're trying to access $pages['page'].
There are two ways to fix this. Add page to the $pages array on the fourth line:
pages = array('home', 'pagetwo', 'contact', 'page');
Or wrap the 43rd line with an if statement:
<?php
$pages = array('home', 'about');
if (isset($pages['page'])) {
echo $pages['page'];
}
?>
However, a far easier method would be to use CSS:
home.php
<html>
<head>
<title>Foo</title>
</head>
<body id="home">
<ul class="menu">
<li id="link-home"><a>Home</a></li>
</ul>
</body>
</html>
style.css
body#home {
// active link styling here
}
I have seen the following thread but it's a bit beyond me...
How can I change the <title> tag dynamically in php based on the URL values
Basically, I have a page index.php (no php in it just named to future proof - maybe now!). It contains numerous lightbox style galleries which can be triggered from an external link by a variable in the URL - e.g. index.php?open=true2, index.php?open=true3, etc.
I would like the index.php title tag - to include existing static data + append additional words based on the URL variable - e.g. if URL open=true2 add "car gallery", if URL open=true3 add "cat gallery", if URL has no variable append nothing to title.
Can anyone assist? I have been searching but either missed the point of posts or it hasn't been covered (to my amateaur level).
Many thanks. Paul.
At the top of your php script put this:
<?php
# define your titles
$titles = array('true2' => 'Car Gallery', 'true3' => 'Cat Gallery');
# if the 'open' var is set then get the appropriate title from the $titles array
# otherwise set to empty string.
$title = (isset($_GET['open']) ? ' - '.$titles[$_GET['open']] : '');
?>
And then use this to include your custom title:
<title>Pauls Great Site<?php echo htmlentities($title); ?></title>
<title>Your Static Stuff <?php echo $your_dyamic_stuff;?></title>
<?php
if( array_key_exists('open', $_GET) ){
$title = $_GET['open'];
}else{
$title = '';
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
The content of the document......
</body>
</html>
http://www.w3schools.com/TAGS/tag_title.asp
http://php.net/manual/en/reserved.variables.get.php
PHP can fetch information from the URL querystring (www.yoursite.com?page=1&cat=dog etc). You need to fetch that information, make sure it's not malicious, and then you could insert it into the title. Here's a simple example - for your application, make sure you sanitise the data and check it isn't malicious:
<?php
$open = "";
// check querystring exists
if (isset($_GET['open'])) {
// if it does, assign it to variable
$open = $_GET['open'];
}
?>
<html><head><title>This is the title: <?php $open ?></title></head>
PHP has lots of functions for escaping data that might contain nasty stuff - if you look up htmlspecialchars and htmlentities you should find information that will help.
Some of the other answers are open to abuse try this instead:
<?php
if(array_key_exists('open', $_GET)){
$title = $_GET['open'];
} else {
$title = '';
}
$title = strip_tags($title);
?>
<html>
<head>
<title><?php echo htmlentities($title); ?></title>
</head>
<body>
<p>The content of the document......</p>
</body>
</html>
Otherwise as #Ben has mentioned. Define you titles in your PHP first to prevent people from being able to directly inject text into your HTML.