I'm currently using include 'header.php' and include 'footer.php' in every page, and as far as I know that's how most people do it. I thought of a way that I personally thought would be better, however. I thought of making index.php, then in the index include the page. This would both eliminate the need for a footer and eliminate the need for include twice in every page. I'm really new to php, however, so I don't know how I would do this. I tried using POST and GET methods, but it doesn't seem to work. What I want to achieve is including pages in the header using a URL such as http://mysite.com/index.php?page=history and then load history.php. If I need to clarify something, just ask. Sorry if I don't accept an answer right away, I'm really drowsy. I'll get to it when I can.
It is not a problem if you include 2 pages in a file, like header.php and footer.php...
Just writing 2 lines of code in each page is not a matter.
You can decide what pages you want to include dynamically in every page by using if statement, instead of passing the page name in the url.
If you'll do it via index.php, you will no doubt do it wrong.
Nothing bad - every newbie does it this way.
Just because you're thinking of includes, while you should be thinking of templates.
You can make it via index.php, no problem. But there should be not a single HTML tag in this index! As well as in the actual page.
No matter if you're doing it in separate pages or via index.php, the scenario should be the same:
Get all data necessary to display particular page.
Call a template.
Thus, your regular page would look like
code
code
code
include 'template.php';
while index.php would look like
get page name
sanitize page name
include page
include 'template.php';
now you can decide what to choose
First off i agree with Meager... Take a look at soem frameworks. Most will use a two step view which essentially does this althoug in a more complex and flexible way.
With that said it would look something like this:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home'; // default to home if no page
if(file_exists($page.'.php')) {
// buffer the output so we can redirect with header() if necessary
ob_start();
include($page.'.php');
$content = ob_get_clean();
}
else
{
// do something for error 404
}
?>
<html>
<head></head>
<body>
<?php echo $content; ?>
</body>
</html>
You could get more complex than that. One thing you want to do uis make sure you dont blindly assume that the page in the $_GET var is safe... make sure the file exists on your server or otherwise sanitize it...
Related
I absolutely don't post a question here in SO unless I really can't find a way to solve my problem myself. I did a lot of googling and was not able to find a solution for this one problem I am about to describe.
Here is the problem. I am creating a templated php website. With templated I mean something like below:
<?php include("header.php");?>
<div id="content">
<div id="main">
<h2><?php echo($page_title);?></h2>
<?php
echo ($page_content);
?>
</div>
<?php include("sidebar.php");?>
</div>
<?php include("footer.php");?>
As you can see here page template ECHOES the content of the $page_content variable between header and footer sections to build the page.
To keep the code clean and separated (in my own way) I have been placing the html content in .txt files (let's say page1_content.txt) and assigning the txt content to this variable ($page_content) as below:
$page_content = file_get_contents("page1_content.txt");
My problem starts when I place some php code in page1_content.txt, lets' call this file page2_content.php (yes, I change the file from .txt to .php). Then I assign the content of this file to $page_content variable as below as usual:
$page_content = file_get_contents("page2_content.php");
Now, when the page template ECHOES page2_content.php contents the php code in it is also echoed as string and not executed, but I am trying to query a database and do some stuff in this file with some php code. I mean, I want the php code inside page2_content.php to be executed and the cumulative html code to be echoed by the "echo" line inside the template file.
How can I achieve this?
Please ask me any questions if you need more info/clarification.
Thanks
EDİT:
As many people here suggested the solution was including the file. Actually, I tried including the file before but it didn't look like it was working, it broke my template, so I though I was on the wrong track and quit the "include" way of doing this. Since everybody here is advising to use include I tried that again. I replaced the php code in "page2_content.php" with a basic 1-line code just to see if it gets executed before adding generated html code without breaking the template and it worked. Apparently my php code had a problem at first place and hence broke my template execution.
Now I have changed the template structure slightly and pages using the template, and it seems to work nicely. Thanks a lot everybody. I have up-voted every answer suggesting that I use include :)
As #Ali suggested, you could include the files. The other option which I highly suggest you do not use is the eval() function.
I think what you want to do is to include your content PHP file, not echo it (as you are doing with header.php and footer.php).
echo($page_content);
Would become as below:
include("page2_content.php");
You've already done this in your footer and sidebar, just use include()
I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.
I've been working on a small page in PHP, one that doesn't need the power of a full-fledged framework behind it. One thing that I'm really missing from previous work in Ruby-on-Rails is the ability to effectively pass content up the page using "content_for".
What I was wondering is, how could you create a page lifecycle that would accomplish this same effect in PHP?
So, here's a simple example:
Let's say you have a template that defines an index page, just a recurring header and menu you want to use on all your pages. So your index.php file looks basically like this:
...header stuff...
<body>
<?php include $file.'.php'; ?>
</body>
...footer stuff...
EDIT: Thanks for the tips on URL security, but let's just assume I'm getting the user request safely :)
Now, lets say in the header you want to put this:
<head>
<title><?php echo $page_title; ?></title>
</head>
It would be nice to be able to specify the title in the included file, so at the url http://example.com/index.php?p=test you're loading test.php, and that file looks like this:
<?php $page_title = 'Test Page'; ?>
... rest of content ...
Now, obviously this doesn't work, because the including page (index.php) is loaded before the variable is set.
In Rails this is where you could pass stuff 'up the page' using the content_for function.
My question is this: What would be the simplest, leanest way that you all can think of to effect this kind of 'content_for' functionality in PHP?
Ideally I'd like suggestions that don't involve strapping on some big framework, but some relatively light boilerplate code that could be used in a lot of different applications.
Never do include $_GET['p']. This opens a huge security hole in your site, as include accepts filenames and URLs, so anybody would be able to read any file on your site and also execute any code on your server. You may want to check and sanitize the value first.
If you need something simple, you may put header and footer in separate files, execute your test.php which would set the variables, capture its output using output buffering, then include the header, output the middle part and include the footer. Example:
<?php ob_start(); ?>
<body>
<?php include $filename.'.php'; ?>
</body>
<?php $content = ob_get_clean();
include 'header.php';
echo $content;
include 'footer.php';
?>
If I understand you correctly (I have not used RoR extensively), you could put your data in a variable or a function. If your content was in a variable, your "test.php" could simply hold all your variables and you could load it at the very beginning of your index file (likewise for a function depending on how complicated your needs are; if you're doing a lot of extra work, you may need to use a function as a variable won't work).
For example, your test.php would look something like this:
<?php
$page_title = "Test Page";
$page_content = "Some sort of content";
// Or
function page_content()
{
// Run some functions and print content at the end
}
?>
Then, in your index.php
<?php include $_GET['p'].'.php'; ?>
...header stuff...
<title><?php print $page_title; ?></title>
<body>
<?php print $page_content; ?>
<!-- OR if function -->
<?php page_content(); ?>
</body>
...footer stuff...
This way everything should load properly. You could also split things up, but that would complicate your structure (especially if there is no need for an elaborate framework, this would be unnecessary).
Good luck!
Dennis M.
Are you worried about XSS? Or are you going to filter/whitelist the "filenames" from the query string?
My answer would be to use mod_rewrite -- if you're using PHP, you're likely using Apache!
You could filter out files with a RewriteCond and your RewriteRule could be:
RewriteRule /index.php?p=(.*)$ $1 [L,QSA]
This may be a different approach than the PHP functionality you were looking for, but it comes to mind...
If jquery is added in globally used header.php across the site then How to stop to load jquery library only for those pages of site which doesn't need actually? If we can't use more than one header.
purpose of question is to not to penalize those page with slow loading which actually don't need.
Your site shouldn't need more than one global-header, if you opt to even use headers to begin with. If it does, just include jQuery on all pages. It's a small cached file, it won't hurt the browsing experience.
By using the google-hosted version, it may be the case that many of your uses already have it cached before they even reach your site.
I have been guilty of pounding my fist into the nail while asking everyone else to move the hammer that's in the way...
Why not tackle the problem from the other end and use jQuery to optimize the first load?
If you have big pages that are already taking a while to download, why not section off the less-performant areas and use $().load() to fill those in?
The page will load quicker (better user experience) and you don't have to be adding any additional processing to pages that don't need it.
Cheers,
-jc
assuming you are loading the jQuery file from a correctly-configured webserver (or from google's CDN), it will be cached and not re-downloaded on each page. Assuming a visitor will hit at least one page on your site that needs jQuery then you really won't gain anything by trying to remove it from loading on pages that don't use any javascript features from the library.
First, use the compressed jquery for production. It's much smaller. Second, IIRC, once jquery is downloaded with the first page, it will be cached and won't need to be retrieved from your server for each subsequent request.
Otherwise, if you really need to explicitly load jquery only on those pages that need it, you would have to have some way for the body of your page to tell header.php that it doesn't need to load jquery. If header.php is loaded before "body.php" then that's pretty hard to do without some fancy output buffering or such.
If you're using a templating system like Smarty you could have a conditional in the master page template to check a $loadjquery flag that you set in body.php before sending the whole page off to be rendered. But that's complicated too.
Your question is very general, some specific would be great, maybe even a link to the site. Personally if you are using a CMS I would try to make some sort of "flag" for that page, or if you are simply loading a page and then loading the header from that page, insert a variable before you load the header and use that as your flag for loading jQuery.
An example:
If a user wants to see www.mysite.com then the following file would be loaded: www.mysite.com/index.php with the following code:
<?php $needJQuery = true;
include('header.php');
echo 'content will go here';
include('footer.php'); ?>
header.php would include something such as this:
<?php if ($needJQuery) { ?>
<script src="/jquery/jquery-min-3.2.1.js" />
etc. for all the content that you need above/below.
<?php } ?>
For the pages that don't need jQuery loaded, you would either leave $needJQuery undefined or you would do as follows:
<?php $needJQuery = false; ?>
Hope this helps,
As stated earlier, modify the header file so it'll check for the presence of flag variable and only output the jquery headers if needed.
If you don't have the ability to modify the header file, you could load it with output buffering turned on and filter the output before it heads out to the client:
<?php
ob_start();
include('header.php');
$header = ob_get_flush();
$cleanheader = some_operation_that_removes_the_jquery_script_tags($header);
echo $cleanheader
?>
I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.