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";
}
Related
I want to place an image, HTML or simply text as a page header on multiple pages, but it is specific to each page, based on the file name (and folder it is in).
So, for example, domain.com/portfolio/index.php gets one image (or text/HTML/CSS), domain.com/portfolio/about/index.php gets another, domain.com/portfolio/contact/index.php gets another and so on.
Basically, I want to update this common element from one file instead of updating a bunch of files. I will usually use either the same image or the same HTML/CC design with different text and/or image in it, so the code example below includes a simplified version of each, just in case.
I've successfully used this in the past for pageheaders on sites but it no longer seems to work (PHP updated or maybe Bootstrap 5 is mucking things up)... it sits in pageheader.php which is then included in the top.php that is used (included) on each page of the site. (And I am not a programmer :) )
Help is always appreciated - thanks!
<?php
$path = ("/portfolio");
$size = ("WIDTH=525 HEIGHT=41 BORDER=0");
$self = $_SERVER['PHP_SELF'];
if (strstr($PHP_SELF,"$path/about.php")) {echo "<h1>About Page Header HTML/CSS Here!</h1>";}
elseif (strstr($PHP_SELF,"$path/index.php")) {echo "Home Page Header Text Here";}
elseif (strstr($PHP_SELF,"$path/design/index.php")) print ("<IMG SRC=$path/images/header_design.jpg $size>");
elseif (strstr($PHP_SELF,"$path/articles/index.php")) print ("<IMG SRC=$path/images/header_articles.jpg $size>");
else {echo "<h1>Hello World.</h1>";}
?>
Note : $PHP_SELF in (strstr($PHP_SELF,"$path/about.php"))
Shouldn't it be $self, e.g. (strstr($self,"$path/about.php"))
<?php
$path = ("/portfolio");
$size = ("WIDTH=525 HEIGHT=41 BORDER=0");
$self = $_SERVER['PHP_SELF'];
if (strstr($self ,"$path/about.php")) {echo "<h1>About Page Header HTML/CSS Here!</h1>";}
elseif (strstr($self ,"$path/index.php")) {echo "Home Page Header Text Here";}
elseif (strstr($self ,"$path/design/index.php")) print ("<IMG SRC=$path/images/header_design.jpg $size>");
elseif (strstr($self ,"$path/articles/index.php")) print ("<IMG SRC=$path/images/header_articles.jpg $size>");
else {echo "<h1>Hello World.</h1>";}
?>
Basically my task is,through the mandatory use of _GET,I'm supposed to make a code that fetches a specific php file when someone types in something like ..php?page=airlines and I dunno if I'm just lacking information or what but this isn't working router.php:
<?php
$nav =array("home"=>"C:\xampp\htdocs\project\home.php",
"flight"=>"C:xampp\htdocs\project\flight-detail.php",
"order"=>"C:xampp\htdocs\project\order-flight.php,",
"testimonial"=>"C:xampp\htdocs\project\add-testimonial.php");
if ( isset($nav[$_GET['page']]) )
{
echo header('Location: ' . $nav[$_GET['page']]);
}
if i understood your question, there are many ways to reach your goal.
I write an example that no change very your code:
<?php
$myPath="C:\xampp\htdocs\project\";
$nav =array("home"=>"home.php",
"flight"=>"flight-detail.php",
"order"=>"order-flight.php,",
"testimonial"=>"add-testimonial.php");
if ( isset($_GET['page']) and !empty($_GET['page']))
{
$myFile=nav[$_GET['page']];//i assume that in page there are only array keys value
echo header('Location: ' . myPath.$myFile);//i.e. I suppose in page there is home output is: "C:\xampp\htdocs\project\home.php"; file
}
else
{
echo 'error: page not found!';
}
An other "easy" solution is to create in first page the link where the user can choose the page:
<a href="C:\xampp\htdocs\project\home.php">HOME<a>
<a href="C:\xampp\htdocs\project\flight-detail.php">FLIGHT DETAIL<a>
....
Hope this helps
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".
I have a page with two links (text link & banner link),
that should lead to the same redirect page
(on my domain).
The redirect would be to a link that shall include a variable,
that indicates which of the two link was clicked.
e.g.:
<?php
header("Location: http://external-domain.com/?ref=[value]");
die();
?>
wheareas the "value" should be "text" / "banner" or something similar.
How can I do this?
I'm not a web programmer at all so I don't have much technical knowledge,
I guess one possible solution (which I would rather avoid) would be to give a separate id for the text link and for the banner, e.g.:
text link:
http://mydomain.com/redirect.php?id=text
banner link:
http://mydomain.com/redirect.php?id=banner
whereas redirect.php would contain:
<?php
$source = $_GET['id']
?>
<?php
header("Location: http://external-domain.com/?ref=<?php print $source; ?>");
die();
?>
But that would mean that I have to use a different id for these internal links;
I would rather find a way to use the same exact internal links (maybe for example, have each link in a "div" or a "class" and get the div/class name somehow, and have them appear as the [value].
*EDIT:
Let me emphasize again: I'm looking for a way to do this without having to use any "?id=[something]" at the end of the text link or the banner link.
Thanks!
If you're already outputting the banner/text do this for the banner
<img src="imageHere.png">
And this for the text
text here
Then catch the id get values with
<?php
$id = $_GET['id'];
if ($id == 'banner'){
echo 'The clicked link was a banner';
}
else{
echo 'The clicked link was text';
}
<?php
$source = $_GET['id']
?>
<?php
header("Location: http://external-domain.com/?ref=<?php print $source; ?>");
die();
?>
should be
<?php
$source = $_GET['id'];
header("Location: http://external-domain.com/?ref=".$source);
die();
?>
Basic concatenation.
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!