Is it possible to add content to <head> from <body> in PHP - php

I'd like to know if it is possible to add content to the <head> section of HTML from the <body>, in PHP.
I know how to do this in JQuery, but I need to the final HTML code to already have the aditional data.
I also know that I can use ob_start() to manage all the content that will be processed, but the reason I'm asking this is because I have some websites already finalized and wanted to know if there is a simpler way to do this, instead of restructure the entire website (and it isn't just one, there are several).
Just for explain better, usually my websites are structured like this:
- I have a "master page", who have all the content there are present in the whole site (like header, footer, etc), kind of like this (it's not this simple - I use validation, friendly URLs, etc - it's for example only):
<?php
$page = $_GET['page'];
<html>
<head>
// All my header content
</head>
<body>
if($page == 'home')
include('pages/home.php');
elseif($page == 'about')
include('pages/about.php');
// etc
// Here comes my footer content
</body>
</html>
?>
Bottom of line: I want to add content to the <head> from some of the pages included.
Since now, thank's for all help.

Maybe you can look at the concept of the code below. What you really want is not clear for me so you can add comment if ever.
<?php
$msg = "<script> function TryOpen(){ alert('Hello World!'); } </script>";
?>
<html>
<head>
<?php echo $msg; ?>
</head>
<body>
<?php
if($page == 'home')
include('pages/home.php');
elseif($page == 'about')
include('pages/about.php');
?>
<input type="button" name="btnAlert" value="Click" onclick="TryOpen();" />
</body>
</html>
For I have no idea what kind of content you want in the <head> tag so I made a script for an example. Hope it can somehow help.

Related

How to get page <title> from content include into front controller

I'm using a PHP based front controller pattern such that index.php provides the page structure and template, and all content for each page is in include files within /pages/.
index.php
/pages/home.inc
/pages/about.inc
/pages/contact.inc
The include pages are mostly simple HTML so that clients can edit the pages without having to get into anything too complex.
The problem with this layout is that because all page information is in the page include, the <title> element can't get populated. I could put a $title variable in each include, but it loads after the head, which is too late:
<html>
<head>
<title><?php echo $title; ?></title> #$title is not set yet!
</head>
<body>
<?php include($content); ?> #now $title is set
</body>
</html>
It's important that the content files are self contained and mostly HTML, but with the ability to have PHP code as well, as I mentioned, because customers will be modifying these and adding too much complexity is a problem. Thus, for example, setting up a separate database of page titles won't work because customers won't update the database when they make new pages.
Edit: a typical page include might look like this.
<h1>Welcome</h1>
<p>blah</p>
<?php include("nav.php"); ?>
<p>more blah</p>
<p>more blah</p>
<p>more blah</p>
<?php
$pageJavascript = "alert('js!');";
$pageTitle = "Cyberdyne Welcome Page";
?>
Options:
1: Use output buffering
<?php
ob_start();
include($content);
$body = ob_get_contents();
ob_end_clean();
?>
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $body; ?>
</body>
</html>
Pros:
The browser gets fully rendered page
More SEO-friendly (than the javascript title update)
No JS required
Cons:
Need to buffer all the page in memory
2: Set some kind of general title and update it later with javascript.
<script type="text/javascript">
with(document) {
window.title = <?php echo json_encode($title); ?>;
}
</script>
Pros:
You keep the same kind of flow You use now.
Cons:
Not SEO friendly
Requires javascript use
If there is a assumption the title is always on the first line:
"My page Title";
$filename = '/pages/home.inc';
$fileLines = file($filename, FILE_SKIP_EMPTY_LINES);
$title = yourFunctionThatStripsKomma($fileLines[0]);
Only bad thing is, is that you have to be sure the first line has the title.

PHP: Hide/show element when visitors visit certain page

I construct my webpages like this:
<?php
include ('header.html');
?>
<p> bla bla bla </p>
<?php
include ('footer.html');
?>
I use session in the header.html to track the user records. The header.html has got three tags, called logo on the left, search_form in the middle, and login/ sign up buttons on the right
Now, the question is that I would like to hide the search_form DIV in the middle by using php in the header.html file if and when the internet users (not registered members) visit the certain page, e.g., register.php, because this DIV is not necessary.
Note: I would like to control it using PHP, but not javascript or anything else.
Can you help me, please?
Thanks
You could use $_SERVER['REQUEST_URI'] to check if the current url is, for example, 'register.php'. Something like:
<? php
if ($_SERVER['REQUEST_URI'] == 'mysite.com/register.php'):
include ('register_form.php');
?>
Of course, this would only work if the url matched exactly, and query strings would break this. But you get the general idea.
Look into creating sessions and user authentication using PHP.
Change your header.html page to header.php.
in header.php check that if current user as a registered user then show the search div or
check current page by your browser url and make decision whether you want to show search div or not.
You can use session to get current user information in header.php
sample code:
header.php
session_start();
if(isset($_SESSION['current_user'])){ //check register user
// show div
}
else {
$page= $_REQUEST['current_url']; // get current page
if($page == 'register.php' || $page == 'whatever' ){ //check pages where you are not show search page
echo '';
}
else {
//show div
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<?php
session_start();
$_SESSION['view'] = $_SERVER['REQUEST_URI'];
if(isset($_SESSION['view']) && $_SESSION['view'] == '/test/index.php') {
?>
<div>head</div>
<?php } ?>
body here
<div>footer</div>
</body>
</html>
This is my sample work and this is works correctly. If my url not equal to /test/index.php it does not show head. You can set your own logic according to this demo work. I think it can help you.
I tried and tried and found out the solution already. Now, I can share it with you guys:
if( (isset($_SESSION['current_user'])) || (basename($_SERVER['PHP_SELF']) != 'register.php') ){
// show the search_form DIV
}
Thanks for your contribution!

How to make php includes for html pages in web site

I'm the first to admit that I'm green when it comes to PHP coding. However many years ago, a colleague gave me a pattern to use for joining PHP with HTML to create web pages. Now, I am looking to revamp the site but I want to know if there is a better way to write it? Currently, I have an index.php page which has a layout similar to this:
<?php
if (! isset($HTTP_GET_VARS['content']) || ! $HTTP_GET_VARS['content']){
$content="home";
}
else
$content=$HTTP_GET_VARS['content'];
//1
if ($content == "home"){
$page_title="Page Title";
$keywords="Keywords found in Meta";
$desc="Description found in Meta";
$style="scripts/style.css";
$popupjs="none";
$storbutnjs="none";
$retreatjs="none";
$rolloverjs="scripts/rolloverjs.js";
$readform_chkjs="none";
$logo="req-files/logo.html";
$sidebar="req-files/sidebar.html";
$main="home.html";
}
//2
if ($content == "about"){
$page_title="Page Title";
$keywords="Keywords found in Meta";
$desc="Description found in Meta";
$style="scripts/style.css";
$popupjs="none";
$storbutnjs="none";
$retreatjs="none";
$rolloverjs="none";
$readform_chkjs="none";
$logo="req-files/logo.html";
$sidebar="req-files/sidebar.html";
$main="about.html";
}
include ("req-files/head.html");
include ($logo);
include ("req-files/navbar.html");
include ($sidebar);
include ($main);
/*include ("scripts/analytics.js");*/
include ("req-files/footer.html");
?>
So, if a person typed http://yourwebsite.com/?content=about They would get the whole About page built in the browser with all required meta, header, sidebar, footer, javascript, css, analytics, etc. Each of those required parts are html files, some may have php scripts for some of the $ callouts like Page Title, Keywords, etc.
One of my problems is when my client wants to change the name of one of the '($content == " ")' to something else. First, I can change the variable, but then I have to redirect the old name to the new name so that we don't lose page ranking.
For instance, http://yourwebsite.com/?content=about needs to be redirected to http://yourwebsite.com/?content=about-us.
Eventually, the client will redirect all or most pages to be more direct, http://yourwebsite.com/about-us. It is believed that this will make the rebuild go more smoothly when the site is turned into a WordPress website.
So, is there a better way to write this? Is there a better way to redirect URLs?
Thank you...
$HTTP_GET_VARS is deprecated. Please try to learn PHP from the official docs.
To answer your problem, another commonly used system is like this:
File: include.php
<?php
function topbanner($title) { ?>
<!doctype html>
<html>
<head>
<title><?php echo $title; ?></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<header>
Site name, Logo, etc.
<header>
<?php }
function footer() { ?>
<footer>
©2012. Your company name. Best viewed in Mozilla Firefox.
</footer>
</body>
</html>
<?php }
Now, create html pages as you would normally do, but make sure the extensions are .php. In those pages, do this.
<?php require_once('include.php'); topbanner("Title of this page"); ?>
<h3>Welcome to this site</h3>
<p>Content content content</p>
<img src="image.jpg" />
<?php footer(); ?>
This is for simple pages. If you need more complex setup, follow the style of fork-cms to redirect pages using .htacess. Either way, pages are renamed means they lose indexing. Why do pages need to be renamed often?
http://php.net/manual/de/function.file-get-contents.php
so you can include html sites in php (var)
$page = file-get-contents('myHTMLSite.html');
and
str_replace('{header}', $header, $page);

php website one page for design

I'm done creating a php website that has 6 pages, and the structure of the pages is the same for each one of them, the only thing that changes is the content, so is the same header, same design and same footer, the only thing that changes like I said before is the content itself.
so i was thinking instead of having many pages, I could have only one design page, and change only the content, what do you recommend?,and how do I do that?, also im not planning installing anything like Typo3, wordpress, joomla or whatever in my server, so I want something i could do using php idk. thank you!
Simplest solution is to create separate files.
header.php
footer.php
menu.php
In header.php put your code from header
<?php ?>
<HTML>
<HEAD>
</HEAD>
<BODY>
...
<? ?>
Same goes for footer and menu files.
Then you can use it by including them.
Your index.php could look like following.
<?php
include("header.php");
include("menu.php");
?>
<h1> This is my content </h1>
<?php
include("footer.php");
?>
This is the easiest option I think for someone who doesn't want to spend using templates, CMS etc. Also you can create function called header that takes $title and changes title of your window. Up to you.
Sounds like you want AJAX. Use prototype. You can make one page, and then use prototype to swap out the content (which could include a PHP page) based on user clicks.
Simple and easy solution:
create footer.php and header.php
and in the header.php you can have something like this:
<?php function top_header($title) { ?>
<html>
<head>
<title> <?php echo $title ?> </title>
</head>
<body>
<?php } ?>
footer.php
<?php function footer() { ?>
</body>
</html>
<?php } ?>
Your index.php could look this:
<?php
include("header.php");
include("footer.php");
top_header("Title of the page");
?>
Hello World!
<?php footer(); ?>

WebDesign: Header file, but with custom Page titles?

I've been using headers to create templates for websites.
It's easy, and very convenient for debugging.
I now face the problem of using head BUT with custom page titles.
If this is my header.php >
<html>
<head>
<title> My Site : ??? </html>
</head>
<body>
</body>
</html>
I need ??? to be replaced for every page.
Is this possible? If so, how? Thank you. : )
Not knowing more about your file inclusion scheme, the simplest way would be:
page2.php
<?php
$pageTitle = 'Page 2';
include 'header.php';
?>
<div>My content</div>
<?php include 'footer.php'; ?>
header.php
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>
footer.php
</body>
</html>
webbiedave's answer is perfectly fine, but in the long run, you should really learn to use either a decent template language (Smarty, Twig), or a PHP framework that has it's own templating. Kohana and Codeigniter are both pretty easy to get into.
If i were to add some code before including the header, will it help?
<?php
$currentPage = "Random Page Title";
include "header.php";
?>
And then use the value in header.php so print the page title?
you could query a DB for the title of a page and then print it using php :)
Edit:
Looking back at the problem , depending on how you have your website designed this may not be the simplest solution. But if you are already using some sort of ID system this should be easy.
Yes, it will help definitely. But you need to do a little customization.
First of all, make sure that you connect to the database, if you want to query / fetch data from database. For this to happen, include the "config.php" page at the very beginning of the script, in which your database connection logic will be present.
Then, write your query to fetch data from that database, and assign that value to the required variable for using it in the header page.
Lastly, include your "header.php" page.
For "config.php" page:-
Logic of Database Connection, like using of "mysql_connect()" & "mysql_select_db()" functions.
For "custom.php" page:-
<?php
include "config.php";
$sql = "SELECT pageTitle FROM db_table WHERE condition = 'something'";
$sql_exe = mysql_query($sql) or die("Error in Fetching Page Title");
if( mysql_num_rows($sql_exe) ) {
$currentPage = mysql_result($sql_exe, 0, 0);
}
else {
$currentPage = "Random Page Title";
}
mysql_free_result($sql_exe);
include "header.php";
?>
Also, if you want, you can always use some class for mysql connection & queries, to fetch data. But this is how it always work.
you can call javascript to change the title of the page dynamically, this is a better solution if you have a master file index.php that calls all other includes
You could also use something like this:
if you married up your php filenames with your page titles
you could use explode or str replace to make it more user friendly to replace commas or underscores for example.
<?php
echo basename($_SERVER['REQUEST_URI']);
?>
or
<?php
// my_page_title.php
$var=basename($_SERVER['REQUEST_URI']);
$pagetitle=str_replace("_"," ",$var);
// my page title
?>
<title> My Site : <?php echo $pagetitle; ?> </title>
Corrected 1 small error in Webbiedave's header.php entry
</html> should be </title>
<html>
<head>
<title> My Site : <?php echo $pageTitle ?> </title>
</head>
<body>

Categories