Change meta description on each page with php after header - php

I ma trying to change dynamically the meta description on each page with php after header.php file.
I currently change my page title by this code:
<?php
require 'config.php';
include 'logout.php';
require 'header.php';
$buffer=ob_get_contents();
ob_end_clean();
$title = "Title of each page";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
//rest of page
?>
and is working.
I tried to do the same for <meta name="description" content="content">
by adding the following code exactly under the title one:
$buffer_meta = ob_get_contents();
ob_end_clean();
$meta_description = "meta content";
$buffer_meta = preg_replace('/(<meta name="description" content=")(.*?)(">)/i', '$1' . $meta_description. '$3', $buffer_meta);
echo $buffer_meta;
But is not working.
On var_dump($buffer_meta) i get string 0 a null result.
Any feedback?

Related

How to include file in PHP with user defined variable

I am trying to include file in string replace but in output i am getting string not the final output.
analytic.php
<?php echo "<title> Hello world </title>"; ?>
head.php
<?php include "analytic.php"; ?>
index.php
string = " <head> </head>";
$headin = file_get_contents('head.php');
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output i am getting :
<head><?php include "analytic.php"; ?> </head>
Output i need :
<head><title> Hello world </title> </head>
Note : Please do not recommend using analytic.php directly in index.php because head.php have some important code and it has to be merged analytic.php with head.php and then index.php
To get the desired output :
function getEvaluatedContent($include_files) {
$content = file_get_contents($include_files);
ob_start();
eval("?>$content");
$evaluatedContent = ob_get_contents();
ob_end_clean();
return $evaluatedContent;
}
$headin = getEvaluatedContent('head.php');
string = " <head> </head>";
$head = str_replace("<head>", "<head>". $headin, $head);
echo $head;
Output will be output string not file string :
<head><title> Hello world </title> </head>
I think your approach is pretty basic (you try to hardcore modify - programmerly edit - the template script, right?) but anyway:
$file = file('absolut/path/to/file.php');
foreach ($file as $line => $code) {
if (str_contains($code, '<head>')) {
$file[$line] = str_replace('<head>', '<head>' . $headin, $code);
break;
}
}
file_put_contents('absolut/path/to/file.php', $file);

How to set dynamic titles in one page template embedding different pages inside the body tag - PHP

According to single page template structure there's only one file called index.php that embeds pages in it using PHP function include_once() inside the body tag against the query string $_GET['page']
<?php $page = $_GET['page']; ?>
<html>
<head>
<title>
<!-- title needs to update according to page here -->
</title>
</head>
<body>
<?php require_once MC_ROOT.'/pages/'.$page.'.php'; // page content goes here like: <div> [CONTENT], <h1> [PRODUCT TITLE] </h1> </div> etc... ?>
</body>
</html>
How do i set dynamic titles inside <title></title> tags which comes before for each page? Pages are supposed to be home, product, contact, about etc. Please suggest any best practice. Thank you
you can use pars_url(This function parses a URL)
for exam
if you address like this
$url = "http://www.ibm.com/product?id=1";
echo parse_url($url, PHP_URL_PATH);
////echo product /////
OR
$url = 'http://www.ibm.com/product/il.php?id=value';
$var = parse_url($url, PHP_URL_PATH);
$var = explode('/', $url);
echo $var[3];
///echo product////
OR
$url = 'http://www.ibm.com/aboutUs.php';
$var = parse_url($url, PHP_URL_PATH);
$var = explode('/', $url);
$var = str_replace(".php","",$var[3]);
echo $var;
///echo aboutUs////
You can include a title-page mapping:
mapping.php
$mapping = [
'home' => 'Welcome on my homepage',
'product' => ['242' => 'My fidget Spinner']
];
$title = '';
if(isset($_GET['page'])){
if(isset($mapping[$_GET['page']])){
$title = $mapping[$_GET['page']];
}
}
if(isset($_GET['page']) && isset($_GET['id'])){
if(isset($mapping[$_GET['page']][$_GET['id']])){
$title = $mapping[$_GET['page']][$_GET['id']];
}
}
you should use ob_start :
ob_start();
$header=MC_ROOT.'/pages/'.$page.'.php';
include($header);
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;

Dynamic content / titles / meta tags

I just created a new website using a tutorial as reference. My problem is mainly the title that doesn't change. But it's not possible to change anything either. Everything is static in the header defined.
I'm brand new to PHP, so any help appreciated.
This is my current code:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
if (isset($_GET['content'])) {
$content = strtolower(trim($_GET['content']));
} else {
$content = '';
}
include_once 'inc/header.php';
switch ($content) {
case 'main':
include 'inc/main.php';
break;
case 'blog':
include 'inc/blog.php';
break;
case 'portfolio':
include 'inc/portfolio.php';
break;
case 'lebenslauf':
include 'inc/lebenslauf.php';
break;
case 'kontakt':
include 'inc/kontakt.php';
break;
default:
include 'inc/main.php';
}
$content = "main";
include_once 'inc/footer.php';
?>
Do you know how to edit this code to be able to change titles or meta tags dynamically or do you know a tutorial for something like a best practice include of PHP files?
Absolutely simplest bare-bones "dynamic" header:
header.php:
<title><?php echo $title ?></title>
index.php:
$title = 'Hello, world!';
include('header.php');
Try below Code.
<?php
$title = "";
$description = "";
$keywords = "";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(strpos($url, 'index') !== false){
$title = "Home | Your Site Name";
$description = "Your Site description ";
$keywords = "Your Site Keywords";
}elseif(strpos($url, 'about') !== false){
$title = "About Us";
$description = "About description ";
$keywords = "key words";
}
?>
<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $description; ?>" />
<meta name="keywords" content="<?php echo $keywords; ?>" />
I'm not sure of the reason why you have routed to pages like this, however i'm guessing your titles/metas are in the header.php file.
To change them you can create an array for each like this:
$titles = array(
'blog.php' => 'title for blog',
'main.php' => 'title for main',
//etc
);
In your switch, assign a variable $include or something the correct page eg:
case:'main':
$include = 'main.php';
include(main.php);
break;
Then use that $include to get the title in your header.php, e.g:
<title><?php echo $titles[$include];?></title>

How to change title of the page after including header.php?

page.php:
<?php
include("header.php");
$title = "TITLE";
?>
header.php:
<title><?php echo $title; ?></title>
I want my title to be set after including the header file. Is it possible to do this?
expanding on Dainis Abols answer, and your question on output handling,
consider the following:
your header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later.
then, you can use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
and that should do it.
EDIT
I believe Guy's idea works better since it gives you a default if you need it, IE:
The title is now <title>Backup Title</title>
Code is now:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
1. Simply add $title variable before require function
<?php
$title = "Your title goes here";
require("header.php");
?>
2. Add following code into header.php
<title><?php echo $title; ?></title>
What you can do is, you store the output in a variable like:
header.php
<?php
$output = '<html><title>%TITLE%</title><body>';
?>
PS: You need to remove all echos/prints etc so that all possible output is stored in the $output variable.
This can be easely done, by defining $output = ''; at the start of the file and then find/replace echo to $output .=.
And then replace the %TITLE% to what you need:
<?php
include("header.php");
$title = "TITLE";
$output = str_replace('%TITLE%', $title, $output);
echo $output;
?>
Another way is using javascript in your code, instead of:
<title><?php echo $title; ?></title>
Put this in there:
<script type="text/javascript">
document.title = "<?=$title;?>"
</script>
Or jQuery, if you prefer:
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "<?=$title;?>");
});
</script>
Expanding a little on we.mamat's answer,
you could use a preg_replace instead of the simple replace and remove the need for a %title% altogether. Something like this:
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$title = "page title";
$buffer = preg_replace('/(<title>)(.*?)(<\/title>)/i', '$1' . $title . '$3', $buffer);
echo $buffer;
?>
you can set using JavaScript
<script language="javascript">
document.title = "The new title goes here.";
</script>
Add this code on top your page
<?php
$title="This is the new page title";
?>
Add this code on your Template header file (include)
<title><?php echo $title; ?></title>
It's very easy.
Put this code in header.php
<?
$sitename = 'Your Site Name'
$pagetitle;
if(isset($pagetitle)){
echo "<title>$pagetitle." | ". $sitename</title>";
}
else {
echo "<title>$sitename</title>";
}
?>
Then in the page put there :
<?
$pagetitle = 'Sign up'
include "header.php";
?>
So if you are on Index.php , The title is Your Site Name.
And for example if you are on sign up page , The title is Sign up | Your Site Name
Every Simple just using a function , I created it .
<?
function change_meta_tags($title,$description,$keywords){
// This function made by Jamil Hammash
$output = ob_get_contents();
if ( ob_get_length() > 0) { ob_end_clean(); }
$patterns = array("/<title>(.*?)<\/title>/","<meta name='description' content='(.*)'>","<meta name='keywords' content='(.*)'>");
$replacements = array("<title>$title</title>","meta name='description' content='$description'","meta name='keywords' content='$keywords'");
$output = preg_replace($patterns, $replacements,$output);
echo $output;
}
?>
First of all you must create function.php file and put this function inside ,then make require under the MetaTags in Header.php .
To use this function change_meta_tags("NEW TITLE","NEW DESCRIPTION",NEW KEYWORDS); .
Don't use this function in Header.php !! just with another pages .
Use a jQuery function like this:
$("title").html('your title');

Dynamic Title Tag in PHP

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");
?>

Categories