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".
Related
I'm a front-end developer who is somewhat familiar with but rarely uses PHP. I'm working on a personal project where I'm mostly just using includes to link PHP files together. Here is my overall basic page structure:
<?php include('header.php'); ?>
<?php include('pagetitle.php'); ?>
Page content goes here.
<?php include('footer.php'); ?>
On pagetitle.php, I have an <h1>,<h2> and background image relating to which page you're on.
My question is, how do I use conditional statements to put all the page titles/subheadings on pagetitle.php and have them switch depending on what page you're on? So for example, I want
<div id="about">
<h1>About</h1>
<h2>About page subheading</h2>
</div>
to show up on about.php, and
<div id="contact">
<h1>Contact Me</h1>
<h2>Contact page subheading</h2>
</div>
to show up on contact.php, etc. etc. ...but only using pagetitle.php on those pages.
The site isn't huge. It would have no more than 10 pages. Also, I do realize I can just use that page title segment on the respective page, but if possible, I want to try this out.
Thanks!
I would do something like this (not tested, but should work with few, if any, changes.)
(Everyone says that, right? :D):
<?php
/*
create a map that contains the information for each page.
the name of each page maps to an array containing the
(div id, heading 1, & subheading for that page).
*/
$pageinfo = array(
"about.php" => array ("about", "About", "About Page Subheading"),
"contact.php" => array ("contact", "Contact Me", "Contact Page Subheading"),
);
function printinfo($pagename) {
/*
This function will print the info for the current page.
*/
global $pageinfo;
$pagename = basename($pagename);
#make sure we have info for this page
if (!array_key_exists($pagename, $pageinfo) {
echo "<p><b>You did not supply info for page $pagename</b></p>";
return;
}
#we do have info ... continue
$info = $pageinfo[$pagename];
#let's print the div (with its custom id),
echo "<div id='" . $info[0] . "'>\n";
#print the headings
echo "<h1>" . $info[1] . "</h1>\n";
echo "<h2>" . $info[2] . "</h2>\n";
#close the div
echo "</div>\n";
}
?>
Then in each page where you wanted your div, you would place this code:
printinfo($_SERVER['PHP_SELF']);
Other:
This way is more flexible than the other ways, at the sacrifice of no conditional statements. (You specifically requested a solution that had conditional statements; however, in the interest of flexibility & maintainability, this example does not use switch statements or if statements.)
Because there are no conditional statements, there is less code to maintain. Granted, you have to setup the array with the information, but if you decided to change the <h2> to an <h3>, you would have to make the change at only one location, etc.
On your pagetitle.php you could do something like this
<?php
$scriptname = basename($_SERVER["PHP_SELF"]);
if ($scriptname == "about.php") {
echo "<h1>About Page</h1>";
}else if($scriptname == "contact.php"){
echo "<h1>Contact Us</h1>";
}
?>
You have to get the string after the domain name so you can use $_SERVER['REQUEST_URI']
$page = $_SERVER['REQUEST_URI'];
if ($page == "about.php") {
echo "<h1>About</h1>"."<br />";
echo "<h2>About page subheading</h2>"."<br />";
}else if($page == "contact.php"){
echo "<h1>Contact Me</h1>"."<br />";
echo "<h2>Contact page subheading</h2>"."<br />";
}
$page = $_SERVER['REQUEST_URI'];
switch($page){
case 'about.php':
echo "<h1>About</h1>";
echo "<h2>About page subheading</h2>";
break;
case 'contact.php':
echo "<h1>Contact Me</h1>";
echo "<h2>Contact page subheading</h2>";
break;
default:
echo "Invalid Request";
}
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!
I have two scripts but I can't make them work together.
1- A simply page views counter
<?php
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];
?>
2 - A Random link from a list but without repeat the links
<?php
if (empty($_SESSION['links'])) {
// first time visit, populate random links in session
$links = array('http://some-site.com', 'http://some-other-site.com', 'http://example.com');
shuffle($links);
$_SESSION['links'] = $links;
}
$link = array_shift($_SESSION['links']);
$_SESSION['links'][] = $link;
?>
For some reason if I use one of them the other will stop to work, both had worked fine but I can't make them work together on the same site.
On the header I have <?php session_start(); ?> but I also moved the script to different parts of the site and I get always the same problem, one stop to work. I also had the <?php session_start();?> at the start of each piece of code but nothing seems to work.
At some point I manage to make both scripts work but the page views counter script was counting from 3 to 3, not from 1 to 1 - Note that the random link script have also 3 values on it; so my guess is that something is incompatible with both scripts
Any help and guide in how or where I need to place the code will be appreciated.
Thanks and sorry for my English
Daniel
try is on the top of the code
just add "$_SESSION['views'] = 0;" to the top once when u run the main script i think it will work
$_SESSION['views'] = 0;
if (empty($_SESSION['links'])) {
// first time visit, populate random links in session
$links = array('http://some-site.com', 'http://some-other-site.com',
'http://example.com');
shuffle($links);
$_SESSION['links'] = $links;
}
$link = array_shift($_SESSION['links']);
$_SESSION['links'][] = $link;
echo "<pre>";
print_r($_SESSION['links']);
echo "</pre>"
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];
FIXED!
I have 2 php pages that both define the variable "title" as something different. However, echoing the variable on both pages results in the first page's variable's value being displayed on both pages. Any idea why and how I could get the variable to change for each page?
first php page:
<?php
$title = "Posts";
echo $title;
?>
This displays "Posts".
second php page:
<?php
$title = "New Posts";
echo $title;
?>
This also for some reason displays "Posts". Shouldn't this page display "New Posts"?
If you are including the second page on the first page before you define $title on the first page, then the included value will be overwritten.
Are all of your variables defined in the global namespace? If so, this problem will be inevitable when you're including PHP files within other PHP files.
You could resolve the problem by properly encapsulating your variables within a class or namespace; for example:
In file one:
<?php
namespace included;
$title = "original title!";
?>
And in file two:
<?php
namespace including;
require_once "file_one.php";
$title = "new title!";
echo \included\$title;
echo \including\$title;
echo $title;
?>
Which will display:
original title!
new title!
new title!
header.php
<?php
$conn = mysql_connect('localhost', '-', '-');
#mysql_select_db('accmaker', $conn) or die("Unable to select database");
?>
<html>
<head>
<title>Mysite.com - <?php isset($pageTitle) ? $pageTitle : 'Home'; ?></title>
</head>
<body>
profile.php
require 'header.php';
$q = mysql_query("SELECT * FROM users WHERE username = '$username'");
$r = mysql_fetch_assoc($q);
$pageTitle = "Profile of $r[username]";
I think you understand what i want
I cant include header.php after the query, because i wont be connected to mysql
waht do you suggest other than having the connection snippet on every page
What do I suggest? A MVC (Model-View-Controller) Framework like Kohana. If you don't want to go that route, break your connection off into its own file:
<?php
# connect
require_once("connection.php");
# load page data array
require_once("page-data.php");
?>
...
<title><?php print $page["title"]; ?></title>
Note here how I have a $page array of data. This will be helpful when debugging later rather than having several independent variables. With an array of page data, I can quickly see all of the information laid out for any given page:
print "<pre>";
print_r($page);
print "</pre>";
Determining your title should be done within page-data.php, rather than on your page:
$config["site_name"] = "Bob's Shoe Mart";
$config["admin_email"] = "bob#shoemart.com";
/* query to get $row['title'] */
$page["title"] = (!empty($row["title"])) ? $row["title"] : $config["site_name"] ;
Not sure of a "best" solution, but we currently include multiple files. We have our "utilities.php" file that connects to the database and provides some nice functions. We then set our page titles and then we include "top.php" which is the layout portion. It doesn't have anything except HTML with a little bit of PHP for display purposes. Looks like this:
include "utilities.php";
$pageTitle = "Welcome";
include "top.php";