Variable auto_prepend_file? - php

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

Related

PHP: How to set dynamic titles while auto_prepend_file is being used?

The title says it all: I want the page to determine the title, but the title is being set before the page is being read (I think). Is there a way to accomplish this, or am I doomed to include the header on each individual page?
Here's what I have:
php.ini:
auto_prepend_file = "header.php"
header.php:
<?php
if (isset($title) == false) {
$title = "foobar";
}
$title = "My Site : " . $title;
?>
<title><?php echo($title) ?></title>
index.php
<?php
$title = "Home"; // ideally this would make the title "My Site : Home"
?>
Instead of using auto_prepend_file, I would just use:
include 'header.php';
An important reason why I wouldn't use auto_prepend_file is, if you move to another server, you'll have to remember to edit the php.ini. If you just include the file, you can move your code to any server.
Also, just like Fred-ii- said, I wouldn't use parenthesis. Also, you are missing a semi-colon after the echo.
To take that a step further, I would create a file called something like $config.php or $vars.php. Include that before everything and have it define all your global variables and constants.
I would check this out: http://php.about.com/od/tutorials/ht/template_site.htm
This is not an ideal answer, but I could use CGI variables to get the name of the page, then turn that into a title.
function get_title($page){
$title = str_replace("/", "", $page);
$title = str_replace("_", " ", $title);
$title = str_replace(".php", "", $title);
$title = ucfirst($title);
if($title = "Index"){
$title = "Home";
} elseif ($title == "") {
$title = 'Foobar';
}
return $title;
}
$title = get_title($_SERVER["PHP_SELF"]);
$title = 'My Site: ' . $title;
As a follow-up to my original comment, I'm posting this as an answer because while it doesn't specifically solve the problem, it addresses the underlying cause.
Disclaimer: The code below has many problems, especially security, it's not meant to be copied directly but only explains the concept.
What you need to do is have a container file that includes your headers and whatever else, and each PHP file is included from there. For example, name your container index.php, and have the following in it:
<?php
include 'header.php';
if ($_GET['page'])
include $_GET['page'].'.php';
include 'footer.php';
?>
Then each PHP page you have will be wrapped in the index.php file, and you can add whatever you want in the header file which will be included in all of your files. That way you don't have to include anything in the individual page files.
The client will access your pages with a query string, such as: index.php?page=test
Again, for security reasons you will still want to include basic checks in each individual file, but technically this can be avoided in you plan for this. You definitely won't need to include huge headers in each file, like MySQL connections etc. Also for security you should have stringent checks on your $_GET variables to make sure that only the pages you want can be included.
I'd define a writeTitle (or similar) function in the header.php file which you're auto_prepending:
header.php
<?php
function writeTitle($title = 'foobar') {
$title = "My Site : " . $title;
return '<title>' . $title . </title>';
}
And then you can just call the function from your page scripts instead of setting a variable:
index.php
<?php
echo writeTitle('Home');

Setting custom page titles for every pages

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!

Change title in browser tab

I'm trying to change the title in browser tab for a child theme of twentytwelve. I wan't it to print out the same title on every page. What the heck is happening?
<?php
function im_awesome_title($title){
$title = "Im awesome!";
return $title;
}
add_filter( 'wp_title', 'im_awesome_title', 20 );
or some like this. script better put in the end of all php tags
<?php
//set title
echo "<script>setTimeout(function(){var tts = document.getElementsByTagName(\"title\");if(tts.length > 0)tts[0].innerHTML=\"My title\"; else {var tt0 = document.createElement(\"TITLE\"); tt0.innerHTML = \"My title\"; document.head.appendChild(tt0);}}, 200);</script>";
?>
Your im_awesome_title($title) function will always return the value of $title when invoked. To print this title on every page, you will need to call the function in the title meta tag of your pages. So it will look like this:
<head>
<title><?php echo im_awesome_title($title); ?></title>
</head>
Of course your function expects an argument, so if you want the same title on every page, it's best to leave out the argument and simply set your $title variable to whatever page title that you want to use on all your pages.
Hope this helps.

Add to page title tag based on variable from URL

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.

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories