Show content depending on url - php

Is it possible to determine what to show depending on the URL?
I have an index file which is:
<?php include './includes/header.php'; ?>
<?php include './includes/menu.php'; ?>
<?php include './includes/content.php'; ?>
<?php include './includes/sidebar.php'; ?>
<?php include './includes/footer.php'; ?>
Note: I have different "content.php"'s
Is it possible to do something like:
If Url = url {
show only content for the url
}
and then have case system like
case: home.php
show some
etc
I know Wordpress can do it. Is it possible with PHP and MySQL and HTML?
EDIT: Instead of content.php i would want show the desired HTML code gotten from my db

Use this function to see your current page. Then use the "switch" case for proper include file:
## Get Current Page / Section
function cur_page()
{
$cur_page='';
if(isset($_SERVER['PHP_SELF']) && $_SERVER['PHP_SELF']!='')
{
$temp_var1 = explode('/', $_SERVER['PHP_SELF']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
else if(isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME']!='')
{
$temp_var1 = explode('/', $_SERVER['SCRIPT_NAME']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
else if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI']!='')
{
$temp_var1 = explode('/', $_SERVER['REQUEST_URI']);
$cur_page = $temp_var1[count($temp_var1)-1];
$temp_var2 = explode('?', $cur_page);
$cur_page = $temp_var2[0];
}
else if(isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME']!='')
{
$temp_var1 = explode('/', $_SERVER['SCRIPT_FILENAME']);
$cur_page = $temp_var1[count($temp_var1)-1];
}
return $cur_page;
}//end func.....

Querying from database.
I don't recommend MySql, and I hope you learn PDO instead, but just
for this example
function get_me_title($page) {
$query = "SELECT * FROM title WHERE title = $page";
$result = mysql_query($query);
foreach($result as $row) {
return $row[$page];
}
}
Now, you can use function .get_me_title('whatever') to query from database, and echo below
if(isset($_GET['page_id'])) {
$page = $_GET['page_id'];
switch($page) {
case "contact";
echo get_me_title('contact');
break;
case "about";
echo get_me_title('about');
break;
case "portofolio";
echo get_me_title('portofolio')
break;
default:
echo 'you are in home page';
}
}else {echo '404 ERROR! The Page you have requested does not exist';}

Instead of including content.php, you can include needed page.
For example, if You build Your urls, where, for example, $_GET['page'] will refer to needed page, then simply You can do this.
$availablePages = array('default' => 'home', 'about');
if (isset($_GET['page']) && in_array($_GET['page'], $availablePages) {
$page = $_GET['page'] . '.php';
} else {
$page = $availablePages['default'] . '.php';
}
include $page;

Related

Is it OK to use an Array Check instead of Switch Statement for dynamic page content?

I'm trying to create a simple static website, but my lesser knowledge in back-end code had me question my abilities. Is there any kind of security risk or anything else I might be overseeing to use an array check instead of switch statement?
For example this is the code I've been using until recently
// Default page
$current_page = 'home';
if(array_key_exists('page', $_GET)) {
$current_page = $_GET['page'];
}
switch ($current_page) {
case 'home':
$page = 'pages/home.php';
break;
case 'about':
$page = 'pages/about.php';
break;
case 'contacts':
$page = 'pages/contacts.php';
break;
default:
$page = 'pages/404.php';
}
and this is the code I've replaced it with. It just makes more sense to me to have the code that would expand in the future (as more pages are added later on) separate from the actual check that never changes, on top of that I think it looks nicer.
$pages = array(
'home' => 'pages/home.php',
'about' => 'pages/about.php',
'contacts' => 'pages/contacts.php',
'404' => 'pages/404.php',
);
// Default page
$page = $pages['home'];
if(array_key_exists('page', $_GET)) {
$current_page = $_GET['page'];
if(array_key_exists($current_page, $pages)){
$page = $pages[$current_page];
} else {
$page = $pages['404'];
}
}
They are both safe, but the second is a bit easier to manage.
Another approach would be something like this:
$subFolder = 'pages';
$current_page = $subFolder . DIRECTORY_SEPARATOR . 'home';
if (array_key_exists('page', $_GET)) {
$current_page = $subFolder . DIRECTORY_SEPARATOR . $_GET['page'] . '.php';
}
if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . $current_page)) {
$page = $current_page;
} else {
$page = $subFolder . DIRECTORY_SEPARATOR . '404.php';
}
echo $page;
This does not require you to edit your code every time you add a new page. The code itself checks if the requested page exists in the pages directory.

How I can create a PHP breadcrumb with $_GET

In my index.php, I use this method to generate my pages:
<?php
$pages = scandir("views/");
if(isset($_GET["p"]) && !empty($_GET["p"]) && in_array($_GET["p"].".php", $pages))
{
$page = $_GET["p"];
}
else
{
header("Location: ?p=home");
}
ob_start();
include "views/$page.php";
$content = ob_get_clean();
include "views/layout.php";
?>
I would like to create a breadcrumb like this:
How can I do that please? Using what I have in my index.php

Error with if statement to include pages in php

I have a group of pages, and I want to include one of them dependent on a variable in url, but the page is always appear is dashboard
link1 : index.php?pth=&page=dashboard
link2 : index.php?pth=modules/institution&page=inst_classification
if statement :
if (isset($page) && !empty($page)) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}else{
$page ='dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
thanks!
You access $page before you write to it. You also never check for the existance of your pth value. Try:
if (empty($_GET['page']) || empty($_GET['pth'])) {
$page ='dashboard';
$pth = '';
}else{
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.$page.'.php');
You probably also need a / here in your include, if modules/institution/inst_classification.php is the file you are looking for:
include('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php'); - but that is not clear from your question.
if (isset($_GET["page"]) && isset($_GET["pth"])) {
$page = htmlspecialchars($_GET["page"]);
$pth = htmlspecialchars($_GET["pth"]);
} else {
$page = 'dashboard';
$pth = '';
}
include ('../admin/template/'.$template_fldr.'/html/'.$pth.'/'.$page.'.php');

Simple PHP Controller, any issues with this code?

I'm trying to build a really simple php controller page for a small site. Here is what I have so far. It seems to work well. Are there any issues I might be missing with doing it this way?
$page = $_GET['p'];
switch ($page)
{
case "":
ob_start();
include "inc/home.php";
$content = ob_get_contents();
ob_end_clean();
break;
case $page:
$page = str_replace("/", "", $page);
if (file_exists("inc/".$page.".php"))
{
ob_start();
include "inc/".$page.".php";
$content = ob_get_contents();
ob_end_clean();
}
else
include "inc/404.php";
break;
}
include("inc/header.php");
echo $content;
include("inc/footer.php");
UPDATE: Here is the final code based on comments that works well.
<?php
$page = (isset( $_GET['p']) && !empty($_GET['p'])) ? $_GET['p'] : 'home';
if( preg_match( '/[^a-z]/i', $page))
{
$page = '404';
}
if( !file_exists( "inc/".$page.".php"))
{
$page = '404';
}
ob_start();
include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");
?>
Your entire script can be rewritten as follows:
$page = ( isset( $_GET['p']) && !empty( $_GET['p'])) ? $_GET['p'] : 'home';
// Only allow alphabetic characters in a user supplied page
if( preg_match( '/[^a-z]/i', $page))
{
$page = '404';
}
if( !file_exists( "inc/".$page.".php"))
{
$page = '404';
}
include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");
However, this is also no longer susceptible to Local File Inclusion, as $page is restricted to only alphabetic characters, and the script will show the 404 page if anything else is submitted.
It's also more efficient as its not using output buffering.

Problem with some simple code

<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages = array($page_clean);
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
}
?>
It does include the page I call for but it echoes "Page not found" also. What am I doing wrong here?
One love
The if block shouldn't be in the loop. Also, you're constructing the array incorrectly. Try:
<?php
// get all files from pages/ with .php extension
$pages = glob('pages/*.php');
$allowed_pages = array();
foreach ($pages as $page) {
// remove path
$page_clean = str_replace('pages/', '', $page);
// put it in an array
$allowed_pages[] = $page_clean;
}
// determine that the lank will be index.php?page=%
$page = $_GET['page'] . '.php';
// load page
if(in_array($page, $allowed_pages)) {
include('pages/' . $page);
} else {
echo "Page not found.";
}
You shouldn’t browse the whole directory on every request just to see if a given file exists. Just check if that specific file exists:
if (strpos($page, '..') !== false || strpos($page, '/') !== false) {
// invalid value, but you better use a whitelist than a blacklist like I did
} else {
if (is_file('pages/'.$page.'.php')) {
// file exists
} else {
// file doesn’t exist
}
}
I'd do it like this:
if(!isset($_SESSION['allowed_pages'])) {
$_SESSION['allowed_pages'] = array_map('basename', glob('pages/*.php'));
}
$page = $_GET['page'] . '.php';
if(in_array($page, $_SESSION['allowed_pages'])) {
include("pages/$page");
}else {
echo 'Page not found.';
}
That only loads the list of pages once per session and gets rid of the explicit loop for cleaning up the page names from the glob.

Categories