Including CSS file depending on php include variable - php

I am trying to include a specific css file depending on the URL provided by the browser.
My website has the following format:
Header information
php include for content
Footer information
I am doing this so when I change my header menu links, I don't have to change every page on the website.
The php include code is as follows:
<?php
$page = $_GET['page'];
$pages = array('main', 'contact');
if (!empty($page)) {
if(in_array($page,$pages)) {
$page .= '.php';
include($page);
}
else {
include('404.php');
}
}
else {
include('main.php');
}
?>
The URL is made up as follows
index.php?page= for example index.php?page=contact
As part of the php include code, when the page=???? element isn't within the array it loads page 404.php which is an error page.
As can be seen, the array currently contains two pages, main (the home page content) and contact (the contact form). If a user tries to load a page called test (index.php?page=test) my webpage will display the 404 page (however doesn't load index.php?page=404 - the URL in browser stays as index.php?page=test.
What I'm trying to achieve is to load 404.css file when page=test(or any other page name not included in the array) is loaded.
Does anyone know how i'd go about achieving this? I've tried writing an if statement in the header to load 404.css however I was using strstr that fetches the browser URL (so test, not 404), therefore the correct css file doesn't get loaded.
Any help is much appreciated (or a better way to achieve what i'm trying to do).
Thanks in advance
Iain

An easy way of doing this is to make use of the ob_* php functions like bellow:
PHP get all the information from within the ob_start and the ob_get_clean functions and concatenate them all together as a single variable $_page_content, that variable can be used anywhere you need.
<?php
$page = $_GET['page'];
$pages = array('main', 'contact');
if (!empty($page))
{
if(in_array($page, $pages))
{
ob_start('ob_gzhandler');
?>
<link rel="stylesheet" href="css/<?=$page?>.css" type="text/css">
<?
include($page . '.php');
$_page_content = ob_get_clean();
echo $_page_content;
}
else
{
include('404.php');
}
}
else
{
include('main.php');
}
?>

Related

Security Issue on Apache/PHP, root and external folders can be accesed

I am learning PHP and Apache configurations, i am using XAMPP Version: 5.6.19. I have a page named default.php, this page will load a header, a footer and a content subpage between them, this content subpage will be saved on a folder named "content". So to load the site showing the content subpage i would write:
localhost/misite/default.php?page=subpage
to do so i have coded the default.php the following way:
<!--INCLUDE HEADER-->
<?php include 'includes/header.php';?>
<!--LOAD CONTET-->
<?php
/*if page is not set, redirect to index*/
if(!isset($_GET['page']) || strlen($_GET['page']) == 0)
{
header("Location: index.php");
die();
}
/*if page is set*/
else
{
/*search page on contet directory*/
$page = 'content/'.$_GET['page'].'.php';
/*if page not found on content directory, redirect to index*/
if(!glob($page))
{
header("Location: index.php");
die();
}
/*if page is found, load as subpage*/
else
{
?>
<main class = "<?php echo basename($page, '.php'); ?>">
<?php include $page;?>
</main>
<?php
}
}
?>
<!--INCLUDE FOOTER-->
<?php include 'includes/footer.php';?>
I coded it this way in order to only allow load of php files of content folder and most important to prevent access from there to another folder by doing the ../ trick, so if someone try that the result would be:
default?page=../.php
and that will produce a redirect to index page instead.
The problem emerged when i tried to have the same functionality with SEF URL's. I coded the following on the .htaccess:
RewriteEngine On
RewriteBase /misite/
RewriteRule ^([a-zA-Z0-9-]*)$ default.php?page=$1
So i could be able to write
localhost/misite/subpage
So i was expecting the same result as the parameter $1 would be now the value for the "page" parameter on default.php and expected that everything else would be exaclty the same, so i didn't expect to be able to access another folder. But when i tried the following:
localhost/../
As result i got to the dashboard page (localhost/dashboard/) which is a page located outside of mi site folder, and if i try
localhost/..img/ i can access the img folder and so on. It looks like it is not even executing my default.php conditional validations.
I am worried if this could be a security issue and worried if i could get hacked by this. And i don't know why this happens. In case this is a security issue, how can i fix it?
The security risk is with this line:
$page = 'content/'.$_GET['page'].'.php';
Without checking, you're allowing any input to search your disk with the subsequent call to glob. Relative paths will be evaluated, letting the user reference any PHP file on your server.
If all of your PHP files are within 'content' and not in deeper directories, one solution is
// Check "page" only contains letters, numbers, underscore
if (!preg_match('/^\w+$/', $_GET['page'])) {
header("HTTP/1.0 404 Not Found");
exit();
}
$page = 'content/'.$_GET['page'].'.php';
Then you can be confident the path in $page is only referencing a PHP file in your content directory.

How can I make php pages appear inside a div?

How can I make PHP pages appear inside a div called contenct, whenever a menu button is pressed?
For example I should bring product menu product.php page to the document body and head, footer will continue well without causing alteration.
I've tried include, but how could it put the link from appearing on the container div?
I hope I have understood!
leave a sample image:
You can use PHP's include() for that purpose.
An example:
<?php
include('head.php');
include('menu.php');
//your normal body code goes here
include('footer.php');
?>
include('file.php'); will read the contents of the php file and it will add / paste the contents in the main file. In this particular example, it will load the contents of head.php, menu.php, and footer.php.
Hope this helps!
Based on your question, im assuming you would like to page to NOT refresh when the navigation button is pressed, and to simply load the contents of a php file into the content area.
The smart way to do this would be to look into using jquery with AJAX, or LOAD to load external content as needed.
PHP has no direct way to manipulate the clients browser without refreshing or loading another page.
if you must do this in php, a very simple approach would be to have each menu item link to a query string. I.E.
HTML: menu.php
Home
Products
Clients
Contact
and to have the index.php file itself run a switch and case I.E.
PHP: index.php
<?php
if(isset($_GET['page']) && $_GET['page'] != '' ){
$page = $_GET['page']; // page being requested
}else{
$page = 'home'; // default page
}
include('head.php');
include('menu.php');
// Dynamic page based on query string
include($page.'.php');
include('footer.php');
?>
This is a very basic example, but might get you pointed in the right direction.
hope this helps
In the php file the user is viewing, put:
include('home.php');
this will execute the contents of the home.php file in the current php file
You could use AJAX and on the event's finish use result $('#content').empty().append(result)
I'd like to add AMAL's answer...
<?php
require('function.php');
include('head.php');
include('menu.php');
//Create a function here to fetch pages
echo '<div id="content">';
echo get_page();
echo '</div>';
include('footer.php');
?>
Then create a function page and add a function that parse the url and gets the php page. (quickly made function, but should do the trick, or help)
function get_page()
{
//http://example.com?page=home
$page = $_GET("page");
$directory = "pages";
if($page){
//security check (anti-hack)
if (!strpos($page,".")&&!strpos($page,"/")&&!strpos($page,"\\")&&!strpos($page,";")){
$path= $directory."/".$page.".php";
if (file_exists($path)){
require ($path);
}else{
echo "<p>Sorry, but that page does not exist.</p>";
}
}else{
echo "<p>Sorry, but those characters aren't allowed !</p>";
}
}else{
$path = $directory."/home.php";
require ($path);
}
}
Then your php page should look like this:
<p>This is the home page</p>
Add this piece of code in the content area of your content area in main file...
<li>BLOG</li>
<div class="container content">
<?php
if(isset($_GET['page']))
{
$page_name = $_GET['page'];
include("/".$page_name);
}
?>
</div>

Layout of a simple php/mysql website

Id like to know what the best way of laying out a simple website,
I used switches so that my website would contain the same layout and then just have a little content area that changes as you go to
myserver/index.php?page=home
or
myserver/index.php?page=settings
Here is some code of my switch:
index.php:
<?php
session_start();
if (!isset($_SESSION['Username'])) {
header("Location: login.php");
}
include("config.php");
include("userinfo.php");
if (isset($_GET['page'])) {
$Page = $_GET['page'];
} else {
} switch ($Page) {
case "logout": {
require("logout.php");
include("layout.php");
break;
}
case "home": {
$PageTitle = "Home";
$PageFileName = "home.php";
include("layout.php");
break;
}
case "music": {
$PageTitle = "Music";
$PageFileName = "music.php";
include("layout.php");
break;
}
I basicly want to know if the above is a good system for haveing different pages with the same layout but a different content section?
I could also use php includes and include bits and pieces as I need, like a header and side bar, but Id like to know what the best system is? or just any advice or anything.
Thanks,
Jason Russell
I personally use the following structure:
main directory: has all the files
includes folder: has two files
Then I create a page, let's call it index.php
<?php
include("includes/header.php");
echo "<h1>Page title</h1>";
echo "<p>Page text...</p>";
include("footer.php");
?>
I then write a script for each page and keep it all separate. Your method above seems extremely complicated and you will get very very confused after not very long!
Also, the best way to split the header/footer is to make the layout as you want it in one file. Then locate the beginning of the main DIV and the end of the main DIV and put the top part in the header, bottom part in the footer.
I tried to keep that as simple as possible. I hope that helps :)
Well, I can assure you that a huge switch/case is not the solution. Look into MVC.

PHP how to open page1, redirect to page2 and show page1 in a div dom?

I have many sub pages, there urls like www.domain.com/sub/page1.php www.domain.com/sub/page2.php... Now when I type there url in browser. they all redirect to www.domain.com/sub/index.php, and the current sub page will show in a div dom in the index.php.
My knowledge is very limited. I only know jqeury.load and php header Location. but it is difficult redirect to index.php then tell index.php, which is the current sub-pages then do a jqeury.load.
One more note: Also should think SEO. maybe jqeury.load is bad for a search spider. maybe should use hash url.
So I ask for a help. is there anybody could give me some good suggestion? or simple worked examples?
Thanks.
In every PHP file (e.g page1.php) use this code:
<?php
if(!defined('INCLUDE')) {
header('Location: index.php?site=' . $_SERVER['PHP_SELF']); //Send the user to the index.php page
die();
}
?>
Insert the content you want here...
And in the index.php file:
<?php
define('INCLUDE', true);
if(isset($_GET['site'])) {
$site = $_GET['site'];
} else {
$site = 'page100.php'; //Put the name of the default page if the user visits index.php here
}
?>
<html>
<head><!-- HEAD CONTENT HERE --></head>
<body>
<div><?php
include($site); //Put the page requested into the div
?></div>
</body>
</html>

Having includes with variables in two places at once

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.

Categories