I have to make some changes on my old website where I'm not using any templating system. I'm loading the content for some pages from a database based on ?page parameter. So I have something like this:
<title>Page title</title>
...
...
...
$page_id = $_GET['page'];
include 'page.php'; //escaping is done in this file
Inside the page.php file I'm actually loading the information about the page. Based on this information I have to change the title of the main page.
I know that this design is not good at all and I wouldn't do this way these days, but to change everything on this website would be too complicated.
Thank you for your ideas.
Try to add php code before title
<html>
<?php
$page_id=$_GET["page"];
include('page.php');
echo "<title>".$page_title."</title>";
?>
<body></body></html>
Inside page.php:
echo '<script>
document.title = "This is the new page title.";
</script>';
How to dynamically change a web page's title?
Enjoy !
<?php
$page_id = $_GET['page'];
if ($page_id == 'first value') {
$title = 'first title';
} else {
$title = 'second title';
}
?>
<title><?php echo $title?></title>
...<?php
include 'page.php'; //escaping is done in this file
Related
So I would like to print name of the current page in the title tag of the head.
I include my head in every page like this:
include 'includes/head.php';
This is my head:
<head>
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?><title>
</head>
I thought this would work, but now it just shows "Head" on every page.
I know I can make it work by just putting the $page variable on every page but I would like to prevent this.
So is there any way to print the name of the current page through the included head.php file without adding anything to every page?
Thanks
EDIT
This is how I fixed it:
$page = pathinfo($_SERVER['SCRIPT_NAME'],PATHINFO_FILENAME);
If you were to create a file head.php with the following content
<?php
$xpage = pathinfo( $_SERVER['SCRIPT_NAME'],PATHINFO_BASENAME );
$ypage = pathinfo( $_SERVER['SCRIPT_NAME'],PATHINFO_FILENAME );
echo "
<!--
with extension
{$xpage}
without extension
{$ypage}
-->";
?>
and include in your regular php pages using include '/path/to/head.php' you should get the desired result ~ you will see two options - with or without file extension.
To add this to the document title simply echo whichever option is preferrable
<title><?php echo $ypage;?></title>
Try this enclosing the $page variable in php tags:
<head>
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?><title>
</head>
You have several problems, first one is curly bracket in front of the echo, the second one is that end title tag is missing forward slash and probably last one is that page variable is not inside php tags...
So your code should look like:
<?php $page = basename(__FILE__, '.php'); ?>
<title><?php echo ucfirst($page); ?></title>
You could use a function like this:
head.php
<?php
function head($page) {
echo "<head>";
echo "<title>".ucfirst($page)."<title>";
echo "</head>"
}
index.php
<?php
include 'includes/head.php';
$page = basename(__FILE__, '.php');
head(page);
I'm trying to build my app with a MVC pattern, to do that I followed a book. In my index.php page I have a button, when I click on that button I want to call my formController to display a form, I'm trying to do that first just showing a simple text with <h1> but it doesnt show any text just a blank page.
Index.php
<?php
//check for errors
error_reporting(E_ALL);
ini_set("display errors",1);
include_once "Models/PageData.php";
$pageData = new PageData();
$pageData->title = "OSeuCondómiono - Gere tudo apartir de uma única plataforma";
$pageData->bootstrap = "<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'rel='stylesheet'>";
$pageData->jquery = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js'></script>";
$pageData->bootstrapScript = "<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>";
$pageData->googleApiFont = "<link href='https://fonts.googleapis.com/css?family=Merriweather|Open+Sans|Oswald|Roboto'>";
$pageData->addCss("Css/style.css");
$pageData->content = include_once "Views/home.php";
$formButton = isset($_GET['form-nav']);
if($formButton){
$pageData->content = include_once "Controllers/loginFormCont.php";
}
$page = include_once "Views/layout.php";
echo $page;
?>
loginFormControler
<?php
return "<h1>HIIIII</h1>";
?>
that <h1> doesn't display. I don't know why.
Did you try echo instead of return. Return is better to be used inside a function. Yours is used outside a function.
I have a .tpl file which contains the HTML code of my webpage and a .php file that I want to use the HTML code in it and replace some variables.
For example imagine this is my file.tpl:
<html>
<head>
<title>{page_title}</title>
</head>
<body>
Welcome to {site_name}!
</body>
</html>
and I want to define {page_title} and {site_name} in my php file and display them.
One way we can do this is to load the page code in a variable and then replace {page_title} and {site_name} and then echo them.
But I don't know that it's the best way or not because I think there will be some problem if the .tpl file is large.
Please help me to find the best way. Thanks :-)
One way you could do it:
$replace = array('{page_title}', '{site_name}');
$with = array('Title', 'My Website');
$contents = file_get_contents('my_template.tpl');
echo str_replace($replace, $with, $contents);
Update: removed include, used file_get_contents()
Cause I searched for this and found this article I will provide my solution:
$replacers = [
'page_title'=> 'Title',
'site_name' => 'My Website',
];
echo preg_replace("|{(\w*)}|e", '$replacers["$1"]', $your_template_string);
You have to get your Template to a String.
For example with
file_get_contents(),
ob_start();
include('my_template.tpl');
$ob = ob_get_clean();
or anything like this.
Hope this will help!?
Here is simple example hope this will work
Your HTML :
<?php
$html= '
<div class="col-md-3">
<img src="{$img}" alt="">
<h2>{$title}</h2>
<p>{$address}</p>
<h3>{$price}</h3>
Read More
</div>
';
?>
Your Array with you want to replace
<?php
$content_replace = array(
'{$img}' => 'Image Link',
'{$title}' => 'Title',
'{$address}'=> 'Your address',
'{$price}' => 'Price Goes here',
'{$link}' => 'Link',
);
$content = strtr($html, $content_replace );
echo $content;
?>
As you mention you can read the file into a string and replace your markers, alternatively you can include the file but in such case rather than use markers insert php fragments to echo the variables like:
<html>
<head>
<title><?php echo $page_title ?></title>
</head>
<body>
Welcome to <?php echo $site_name ?>!
</body>
</html>
In such case you don't need to run str_replace on the whole template. It also alows you to easily insert conditions or loops in your template. This is the way I prefer to handle things.
I use something similar to the above but I am looking for a better way of doing it as well.
I use this:
$templatefile = 'test.tpl';
$page = file_get_contents($templatefile);
$page = str_replace('{Page_Title}', $pagetitle, $page);
$page = str_replace('{Site_Name}', $sitename, $page);
echo $page;
sorry to bring up an answered thread but I am looking at finding better ways to do this.
I am currently playing with jQuery to do this too so I can have dynamic pages without the full reload. For example:
<div id="site_name"></div>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'data.php',
data: {
info: 'sitename'
}
success: function(data){
$('#site_name').html(data);
//the data variable is parsed by whatever is echoed from the php file
}
});
</script>
sample data.php file:
<?php
echo "My site";
?>
Hope this might help others too.
I am trying to dynamically populate the title tag on a website. I have the following code in my index.php page
<?php $title = 'myTitle'; include("header.php"); ?>
And the following on my header page
<title><?php if (isset($title)) {echo $title;}
else {echo "My Website";} ?></title>
But no matter what I do, I cannot get this code to work. Does anyone have any suggestions?
thanks
This works (tested it - create a new folder, put your first line of code in a file called index.php and the second one in header.php, run it, check the title bar).
You should double check if those two files are in the same folder, and that you're including the right header.php from the right index.php. And ensure that $title is not being set back to null somewhere in your code.
Learn more about Variable Scope here.
Edit: Examples of visible changes would be:
TEST1<?php $title = 'myTitle'; include("header.php"); ?>
<title>TEST2<?php if ...
Are you including the header file before or after you set the title variable? If you're including it before, then of course it won't be set.
if you're doing something like this in your index.php:
<?php
include('header.php');
$title = "blah blah blah";
?>
then it won't work - you include the header file and output the title text before the $title variable is ever set.
try to declare the variable before using it
$title = '123';
require 'includes/header.php';
Hi Try this old school method ..
In your Header file (for e.g. header.php)
<?php
error_reporting(E_ALL);
echo '<!DOCTYPE html>
<!--[if IE 7 ]><html class="ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="ie8" lang="en"><![endif]-->
<!--[if IE 9 ]><html class="ie9" lang="en"><![endif]-->
<!--[if (gte IE 10)|!(IE)]><!-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<!--<![endif]-->
<head>';
?>
<?php
if($GLOBALS['title']) {
$title = $GLOBALS['title'];
} else {
$GLOBALS['title'] = "Welcome to My Website";
}
if($GLOBALS['desc']) {
$desc = $GLOBALS['desc'];
} else {
$desc = "This is a default description of my website";
}
if($GLOBALS['keywords']) {
$keywords = $GLOBALS['keywords'];
} else {
$keywords = "my, site, key, words";
}
echo "\r\n";
echo "<title> ". $title ." | MyWebsite.com </title>";
echo "\r\n";
echo "<meta name=\"description\" content='". $GLOBALS['title']."'>";
echo "\r\n";
echo "<meta name=\"keywords\" content='".$GLOBALS['title']."'>";
echo "\r\n";
?>
In you PHP Page file do like this (for example about.php)
<?php
$GLOBALS['title'] = 'About MyWebsite -This is a Full SEO Title';
$GLOBALS['desc'] = 'This is a description';
$GLOBALS['keywords'] ='keyword, keywords, keys';
include("header.php");
?>
I assume your header is stored in a different file (could be outside the root directory) then all the above solutions will not work for you because $title is set before it is defined.
Here is my solution:
in your header.php file you need to set the $title to be global by: global $title; then echo it in your title so:
<?php global $title; ?>
<title><?php echo isset($title) ? $title : "{YOUR SITE NAME}"; ?></title>
Then in every page now you can define your title after you have included your header file so for example in your index.php file:
include_once("header.php");
$title = "Your title for better SEO"
This is tested and it is working.
We can also use functions and its a good way to work on real time web sites.
Do simple:
create an index.php file and paste these lines:
<?php include("title.php");?>
<!doctype html>
<html>
<head>
<title><?php index_Title(); ?></title>
<head>
</html>
-- Then
Create a title.php file and paste these lines:
<?php
function index_Title(){
$title = '.:: itsmeShubham ::.';
if (isset($title)){
echo $title;
}else{
echo "My Website";
};
}
?>
It will work perfectly as you want and we can also update any title by touching only one title.php file.
<?php
echo basename(pathinfo($_SERVER['PHP_SELF'])['basename'],".php");
?>
This works. Since I'm using PHP I don't check for other extensions; use pathinfo['extension'] in case that's required.
You can achieve that by using define(); function.
In your header.php file add following line :
<title><?php echo TITLE; ?></title>
And on that page where you want to set dynamic title, Add following lines:
EX : my page name is user-profile.php where I want to set dynamic title
so I will add those lines that page.
<?php
define('TITLE','User Profile'); //variable which is used in header.php
include('header.php');
include('dbConnection.php');
?>
So my user-profile/.php file will be having title: User Profile
As like this you can add title on any page on your site
Example Template.php
<?php
if (!isset($rel)) {$rel = './';}
if (!isset($header)) {
$header = true;
?><html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<?php } else { ?>
</body>
</html><?php } ?>
Pages Your Content
<?php
$rel = './'; // location of page relative to template.php
$pageTitle = 'This is my page title!';
include $rel . 'template.php';
?>
Page content here
<?php include $rel . 'template.php'; ?>
I'm using your code in my project and it works properly
My code in header:
<title>
<?php
if (isset($title)) {echo $title;}
else {echo "عنوانی پیدا نشد!";}
?>
</title>
and my code in index.php:
<?php
$title = "سرنا صفحه اصلی";
include("./include/header-menu.php");
?>
My website's pages are (or will) all be identical, except for the content of the #main div. So I was thinking in the <head> I could do <?php $page = "home.html"?>, where home.html is the bare contents (not a full html page - no <html>, <head> etc.) of the main div for the home page. So then inside <div id="main"> and </div> I could have <?php include($page);?>. Then the reason I'm asking this question is I want to change $page when a link is clicked. How can I do this? Thanks.
You could make the links be like this:
Other Page
Then also in the top of the page where you set page to the value of $_GET['page']
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'] . ".html";
} else {
$page = "home.html";
}
?>
Your link has to be like:
home.php?page=test
You will get the value in your page variable like this:
if(isset($_GET['page']))
$page = $_GET['page'].'.html';
else
$page = 'index.html';
You can do something like:
http://yoursite.com/index.php?page=test.html or http://yoursite.com/index.php?page=test (and append .html later).
For instance:
<?php $page = preg_replace('/[^A-Za-z]/','', $_GET['page']);
$path = 'pages/'.$page.'.html'
if (file_exists($path)){ $output = file_get_contents($path); }
else { header("HTTP/1.0 404 Not Found");
$output = file_get_contents('pages/404.html'); }
?>
(Putting the rest of your file after the php, for the 404 header to work.)
Then, you also can use apache rewrites:
Rewrite Engine On
Rewrite Rule ^([A-Za-z]+)$ index.php?page=$1
Then use links like http://mysite.com/page_name
Then in the main div:
<?php echo $output; ?>