Making a site WITHOUT frames - php

I want to make my homepage, without frames, should i just split up my design on index.php so it is header.php/footer.php, and then just include them on every page?

Yes, you can split your index.php into header.php/footer.php and then just include them on every page.
Note that your pages can be not static HTML but php scripts, to show multiple pages with one script.
I'd suggest also to have not a commonplace structure like
include 'header.php';
//do some stuff
include 'footer.php';
but another structure, much more useful:
//do some stuff, retrieve all data.
include 'header.php';
include 'page.php'; //include page template
include 'footer.php';

I suggest you use a framework. Most frameworks (if not all) have simple template systems, so you don't have to repeat code.

The problem with the suggested solution of including stuff in every page of your site is that you have to update all the pages of your site if you want to include another thing, say a sidebar.
A better idea is not to have a script--page connection at all. So you don't write a php file per page you want to show. Instead, use one front controller file, most use index.php in the root of the website. And then use Apache mod_rewrite or other server techniques to have flexibility in the URL's of your site. Then let index.php map different URL requests to serve different pages, you can then put all the pages of your site into a database or somewhere else.
This way there's only one point in your site that includes the templates for the header and footer, so that's easily changeable, and you can use the root of the site to serve AJAX requests, in which you won't want to output HTML but JSON for instance.
Afaik this is a good way of going about it.

Another idea would be to have just one single point of entry which is called with a GET parameter, e.g ?site=about. Your index.php could look like this:
<?php
// whitelist of allowed includes
$allowedIncludes = array('home', 'about', 'error404'); // etc.
// what to include if ?site is not set at all / set to an illegal include
$defaultInclude = 'home';
$errorInclude = 'error404';
// if site is not set, include default
$site = (empty($_GET['site'])) ? $defaultInclude : $_GET['site'];
// if site is illegal, include error page
$include = (in_array($site, $allowedIncludes)) ? $site : $errorInclude;
// actual includes
include 'header.php';
include $include.'.php';
include 'footer.php';
Thus you only have to include header.php and footer.php once and have full control about what is allowed and what is not (the included files could be in a directory that only php has access to). While your index.php handles the request, home.php, about.php do not have to know about header.php and footer.php (you could easily replace them at a later point in time).
If you do not like http://www.example.com/?site=about, you can look into mod_rewrite and friends.

You may want to set a session for that. A session variable exists as long as a visitor is on your website:
<?php
session_start(); // Remember that session_start(); must be the first line of your PHP and HTML-code
if($add_a_message){
$_SESSION['message'] = 'Message';
}
if($destroy_message){
$_SESSION['message'] = '';
}
// echo this message
if(isset($_SESSION['message']) && strlen($_SESSION['message']) > 0){
echo '<strong>' . $_SESSION['message'] . '</strong>';
}
?>

Related

Include PHP file with condition opened but closed in another included PHP file

I would like to include at the beginning of my script a PHP file that open a IF condition. Then i write my script, and to finish I include another PHP file that close the conditon.
This bring me to a "Parse error: syntax error, unexpected end of file in ..." error.
This will be better to understand with this simple example :
header.php
if(aConditionalTest()) {
footer.php
} // endIf
mypage.php
include_once 'header.php';
echo 'my awesome content';
include_once 'footer.php';
FYI: I would like to do this for example :
to check everywhere that a user is authorized before displaying the content
implement a webpage caching system (see http://www.phpfastcache.com/ in "Example" section, "Caching Whole Webpage")
THANKS!
edit : Explain more precisely WHY I want to do this for using phpfastcache :
http://www.phpfastcache.com/ says :
Caching Whole Webpage PHP Cache whole web page :
You can use phpFastCache to cache the whole webpage easy too. This is simple
example, but in real code, you should split it to 2 files:
cache_start.php and cache_end.php. The cache_start.php will store the
beginning code until ob_start(); and the cache_end.php will start from
GET HTML WEBPAGE. Then, your index.php will include cache_start.php on
beginning and cache_end.php at the end of file.
That's just what I try to do!
According to their piece of code below, this brings to the situation where the condition is opened in "cache_start.php" and then closed in "cache_end.php"
cache_start.php
use phpFastCache\CacheManager;
$cache = CacheManager::Memcached();
$keyword_webpage = md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
// try to get from Cache first.
$resultsItem = $cache->getItem($keyword_webpage)
if(!$resultsItem->isHit()) {
ob_start();
cache_end.php
// GET HTML WEBPAGE
$html = ob_get_contents();
$resultsItem->set($html)->expireAfter(1800);
$cache->save($resultsItem);
}
echo $resultsItem->get();
mypage.php
include_once 'cache_start.php';
// my awesome content to cache goes here...
include_once 'cache_end.php';
myotherpage.php
include_once 'cache_start.php';
// my other great content to cache goes here...
include_once 'cache_end.php';
So the reason WHY I want to put the phpfastcache code in 2 separate files is that I have many different PHP pages to cache, so I would like to avoir repeating all this code on each page...
Hope this edit will help you better understand why I would do that, even if I understood, as I feared, that is is not possible.
Give it a try:
how can I achieve this ?
Do it the evil way and eval all instead of including :) Like
eval(file_get_contents('header.php').'<?php echo "my awesome content";?>'.file_get_contents('footer.php'));
That can be a solution, if you want to join the dark side :)
SideNote: In this solution, you have to keep an eye on global variables!!
But please, thing about the fact, that you want to spread conditions over seperate files, what in my opinion is very very very bad practise.
Did i really answer this 8]
I try it in other way.
Only rule: works only in global space (where else :-))
So you want to open an if() in cache_start.php and close it cache_end.php. (for ob_cache reasons)
But if the condition isn't changed why not doing the condition twice!
In each file test for if(condition)!
Or set up an variabale like $cach_op_started=true and test for it in the second if() in cache_end.php
Thing boths should work for you.
Its a little funny that i didnt see that solution at the first time :)
Last Note:
You can also use auto prepend and append files in PHP if you want to.
That can be configurated in php.ini.
The files will automaticly loaded before and after an script, always.
http://www.webdevsecrets.com/using-phps-auto_prepend_file-and-auto_append_file/
Have a nice time.
So I understand that the problem is that when you don't want a certain user to see the contents of a page, the rest of the page isn't loaded and that is whats causing the error?
If so, why don't you just always include the files and in the specific page you set the conditions for who can view what?
I use ob_start() in my header, and ob_end_flush in my footer which works great.
and then check with my SESSION variables on the specific page's content if the logged in user has the right to see the content, else display a message like:"You are not authorized to see this content"

Application Entrypoint

I'm building an application and using index.php as and entry point to different modules. I noticed SugarCRM does this and it appears like a good idea.
The URL Looks like this
http://www.mypage.com/index.php?mod=log&pag=login
Where mod is the module and pag is the page
The index.php looks line this:
<?PHP
define('INCLUDE_CHECK',true);
// Class Loader
require ('app/inc/app_autoload.php');
// HTML Header with js and css links
require ('header.php');
// Content Page
$url_module = $_GET["mod"];
$url_page = $_GET["pag"];
$content = $url_module."/".$url_page.".php";
// For the above URL $content = log/login.php
if (!file_exists ($content)) {
require ($content);
}else{
// Handle Error
}
// Footer
require ('footer.php');
?>
Is this safe?
If it's safe, Is it in line with practices?
This can be potentially unsafe. Depends on all the other PHP files that PHP can open. If all of them are class files that don't execute anything, then you're safe. However, if any of them execute something automatically...maybe not.
Let's say that you have PHP files inside a folder:
/secured/file.php
And let's say that the folder has an .htaccess that prohibits anyone from navigating to the page directly. Or better, let's say it's above your root directory. However, the hacker sends "../secured" as the value of mod and "file" as the value of page. In such a case, PHP may allow the person to include that file, and if it self-executes, it may have unintended consequences.
This is why Zend Framework requires explicit configuration of all MVC paths. Other frameworks allow for a some dynamic inclusion, but they often do something like append "Controller.php" to the end of the string, which ensures that the file included must be a Controller...and thus intended to be included in such a way.
When it comes to security, the best thing you can do is make sure that YOU...with all the knowledge of the entire server...can't open up any file that you don't want to be opened by someone else. If you can't get the code to do it, knowing what files are there, then you have implemented some decent (though likely still not flawless) security.

how to protect a php page where there is no form too check against

im trying to finish my site and ensuring that the user cannot see anything that might help them in malicious ways or give them a bad experience on the site.
So for my pages where e.g login.php i check the request method, if its post continue if not then 404 etc.
However i have a couple of pages that gather some information from the database and i include them in the page. Some of them are quite large / complex so i prefer doing this to keep things tidier.
How can i go about redirecting the user to a 404 if they directly access these pages instead of them just being included?
Thanks. Hope you know what i mean! :)
<?php // top file, eg login.php
define('IN_SCRIPT', true);
include('infopage.php');
?>
<?php // included file, eg infopage.php
if (! defined('IN_SCRIPT')) {
// log message, throw header, etc.
// this is a direct access
exit(0);
}
// do whatever
?>
Alternatively, consider moving your info pages out of the web visible space.
I think that you can use some simple tricks.
where you want to include files, instead of simply
include('db.php')
do:
$including = 'yes';
include('db.php');
and in first lines of db.php:
if (!isset($including)) {
//show 404
exit;
}
//db job
so it does it's job if included, and shows a 404 if it is called directly.
Alternatively:
the first trick (and DEFINE) may be safer but if you don't want to change every file that includes the file;
just in db.php:
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
//show 404
exit;
}
//db job

How do I make index.php will control anything in PHP

Firstly, I don't know what to call this thing :) I want to know the key, structure and example how to achieve my goal.
Example, I don't want create separate file like register.php, login.php, about.php faq.php. Here I want the register, login about, faq ,etc will handle by index.php by example, maybe something like index.php?p=register
How do I create page something like that and what this structure called in PHP programming. Let me know.
In index.php?p=register the part after ? is called "Query String". PHP will by default parse it for you and provides the superglobal $_GET. Just try it out yourself
var_dump($_GET);
To provide a more appropriate answer using Neals code, use basename to filter out non-essential file information:
$page = isset($_GET['p'])?basename($_GET['p']):'main';
include_once "$page.php";
You could also create a "white list" to ensure that only the proper files get included:
$whiteList = array('faq', 'register', 'profile');
$page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';
include_once "$page.php";
Both ways should be secure, obviously, the white list will be a bit more so. This tact, depending on how you do is generally referred to as "BootStrapping" IE, one entrance page to access the rest.
UPDATE
To further the security, I would set a variable, $included would be sufficient, to add to the pages that are being included. This would prevent direct access to them (assuming that register_globals is turned off like it should be, so something like:
$whiteList = array('faq', 'register', 'profile');
$page = (isset($_GET['p']) && in_array($_GET['p'], $whiteList))?basename($_GET['p']):'main';
$included = true;
include_once "$page.php";
Then on $page.php at the top you would have something like:
<?php
if (!$included)
die('Accessing the file directly is not allowed.');
Which would prevent calls to http://yoursite.com/register.php from being allowed to dish out the file. This has it's negatives to it. Instead of putting the files you are going to be including in the webroot, I would put them outside of the webroot or in an .htaccess protected directory, which would ensure that users could not access them directly and must access them through the index.php.
I'm not sure what the whole thing is called, but if you're using index.php like that, it's called a FrontController. It's how MVC frameworks work:
/index.php?q=ctrl/action
/index.php/ctrl/action
/ctrl/action
They're all handled by/in index.php using "ctrl/action"
You want to look up php templates or even html iframe. There are several ways to do this, but some are better than others. In asp.net it's called a MasterPage. Hopefully some of these terms help you out.
If you really want to do something like this, then you can use the get field, but you need to predefine your pages, so for this request: index.php?p=my_page
<?php
$page = $_GET['p'];
$pages = array(
'my_page' => 'mypage.php',
'another_page' => 'another.php',
...
);
$include = $pages[$page];
if(!empty($include)) {
include_once($include);
} else {
echo 'No such page';
}
?>
This keeps the include completely separate from what is passed on the URL so there is no chance for risky things to get passed.

How to use PHP include to insert an HTML stub across all pages in a website

I am developing a simple website. It will have close to 20 pages. It has a 3 level hierarchy.
Home
MenuStub
Category1
Page1
Page2
Category2
Page1
Page2
....
....
....
The main navigation will have 4 - 5 items representing each 'category'
This will be constant for all the pages. I am not even planning to
highlight the current category or anything.
Previously I decided to put the menu HTML stub alone in a separate file
and use PHP include to include it in all pages.
But, relative paths might be frustrating. Assume that the menu stub
file is located at the root directory.
So, in the root-level pages, the php include will read like
include "menustub.html";
in the second level pages, it should say
include "../menustub.html";
and in third level pages, it should say
include "../../menustub.html";
First, is this the best way to include a single file
across all pages in a website?
Second, if the website grows big, and many more levels
are added, maintaining this will be a problem. If I suddenly
decide to move an entire set of pages one (or several) levels
up or down, I should manually go and change the relative paths
in each file.
Am I missing something here? Is there a universal way to point
to a particular file, that every page will understand, regardless
of where it is located?
What is the best way to have a stub and include it in all the pages
without having these maintenance nightmares?
Common ways to solve this problem is either by using include_path: In your config, add the dir with such files to include path, and you can simply do
include "menustub.html";
from anywhere.
See http://se2.php.net/manual/en/ini.core.php#ini.include-path
It can be set from php.ini and in code. Not sure if it can be set in .htaccess files
Another way is to set a root directory variable and always use it:
include "{$rootDir}/menustub.html";
There is also the option of using auto append/prepend, which means you tell php to always append or prepend a file, see http://se2.php.net/manual/en/ini.core.php (auto_prepend_file)
$rootDir can either be set from configuration, or automatically using $_SERVER['DOCUMENT_ROOT']. The former is good if you use it for shared files (shared between several web apps), the latter for convenience if the files are located under one webapp directory strucure.
It would be much more dynamic to have the index file do all the including, and use GET parameters to tell it which page is to be include.
For example, consider a directory structure like this:
/
index.php
/ui
header.html
menu.html
footer.html
Cat1/
Page1.html
Page2.html
Cat2/
Page3.html
Page4.html
If you were to always call the index file, including the name of the category and page you wanted to see, like: index.php?category=Cat1&page=Page1, you could do something like this:
<?php
// Include a header and a menu, defined in their own HTML files.
include('ui/header.html');
include('ui/menu.html');
// Set up a list of valid categories and their sub pages.
$pages = array(
'Cat1' => array(
'Page1',
'Page2'
),
'Cat2' => array(
'Page3',
'Page4'
)
);
// Find the category and page to use.
if(isset($_GET['category'], $pages[$_GET['category']])) {
$category = $_GET['category'];
} else {
$category = 'Cat1';
}
if(isset($_GET['page'], $pages[$category][$_GET['page']])) {
$page = $_GET['page'];
} else {
$page = 'Page1';
}
// Include the selected content page.
include("ui/{$category}/{$page}.html");
// Include a footer
include('ui/footer.html');
?>
This way you can expand the content as far and deep as you want without having to repeat your includes in every single new file.

Categories