I have made a function that take in the current page id and based on that result will either show two .php file or just one .php file.
Following is what I have written. Have I approached this in the right way?
<?php
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
foreach($pages as $page){
if($page==$id)
$match = true;
}
if($match) {
include("dir/file_1.php");
include("dir/file_2.php");
}
elseif (!$match) {
include("dir/file_1.php");
}
}
}
?>
The $pages variable holds the $page_id array i.e.$pages = array('home', 'thank-you');
each .php file has a $page_id i.e index.php has $page_id = "home";
The array is a list of the matching $page_id's:
$pages = array('home', 'thank-you');
The call would then be:
get_search_or_nav($page_id);
Any help or advise would be appreciated.
I just will do this:
$id = $page_id;
$pages = array('home', 'thank-you');
$match = in_array($id, $pages);
The iteration is not necessary
There is no need for the foreach loop. PHP has inbuilt functions to handle what you want (in_array()): I'd change your function to something like this:
function get_search_or_nav($page_id) {
if (isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
// make sure file is in allowed array (meaning it exists)
if(in_array(id, $pages)) {
include("dir/file_1.php");
include("dir/file_2.php");
return true;
}
// no match, so include the other file
include("dir/file_1.php");
return false;
}
}
You could approach your function in following way:
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$pages = array('home', 'thank-you');
// You could do this with for loop
// but PHP offers in_array function that checks
// if the given value exists in an array or not
// if found returns true else false
$match = in_array($page_id, $pages);
// you are including this in either case
// so no need to repeat it twice in both conditions
include("dir/file_1.php");
// if match include file 2
if ($match) {
include("dir/file_2.php");
}
}
// you might want to throw Exception or log error here
// or just redirect to some 404 page or whatever is your requirement
}
in_array reference
Related
I'm not really understanding why this is, but Pager is producing paginated results like the following:
http://www.mywebsite.ca/reports-publications/reports/?field_executive_summary_value=&field_publication_date_value[value]&field_report_type_tid_selective=All&field_natural_resource_region_tid_selective=All&field_forest_district_tid_selective=All&field_keywords_tid_selective=All&page=1#
Instead of simply:
http://www.mywebsite.ca/reports-publications/reports/?page=1
Additionally, "page=1" represents the second page ... as in an array of pages where 0 is actually the first result.
Does anyone know why Pager is producing links like this?
I was able to fix the page number issue by altering pager.inc file.
in pager_find_page function,
function pager_find_page($element = 0) {
$page = isset($_GET['page']) ? $_GET['page'] : '';
$page_array = explode(',', $page);
if (!isset($page_array[$element])) {
// Change here
// $page_array[$element] = 0;
$page_array[$element] = 1;
}
// Add this
$page_array[$element]--;
return (int) $page_array[$element];
}
and, in theme_pager_link function,
if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
// Change here
// $parameters['page'] = $new_page;
$parameters['page'] = $new_page + 1;
}
Creating a block builder that loops through blocks pulled form database in order.
if( loop_blocks()) {
while( loop_blocks()) {
if( have_block('standard-content-block')) {
echo 'standard-content-block';
}
elseif( have_block('executive-intro-block')) {
echo 'executive intro block';
}
}
}
My function loop_blocks pulls the blocks from the database in order and set the array as a global variable:
function loop_blocks() {
global $db;
$page_id = get_page_id();
$GLOBALS['loop_position'] = 0;
$loop_position = $GLOBALS['loop_position'];
$stm = $db->prepare("SELECT * FROM page_blocks WHERE page_id = :id ORDER BY `block_order` ASC");
$stm->execute(array(':id' => $page_id));
$res = $stm->fetchAll();
$GLOBALS['block_loop'] = $res;
if(!$res) {
return false;
} elseif(!$GLOBALS['block_loop'][$loop_position]) {
return false;
} else {
return true;
}
}
The function have_block gets the current loop position and determines whether the name as determined, exists in the array and increases the loop position:
function have_block($block_name) {
$loop_position = $GLOBALS['loop_position'];
if(!$GLOBALS['block_loop'][$loop_position]) {
return false;
} elseif(!$GLOBALS['block_loop'][$loop_position][block_name] = $block_name) {
return false;
} else {
$GLOBALS['loop_position'] = $loop_position+1;
return true;
}
}
This returns an infinite loop however and I can't figure out a way to move the while loop onto the next step?
EDIT I'm using a while loop because the function have_block will set-up a global variable for the current block id. This will then be used within a function called the_element. Such as:
if( loop_blocks()) {
while( loop_blocks()) {
if( have_block('standard-content-block')) {
the_element('heading');
}
}
}
If I don't use the function have_block to set this up, then I'd need to pass the block id from the foreach loop into every element as a second argument.
I fixed this by, as #Jim, noted I was re-setting the loop_position within loop_blocks() which was why the while loop was repeating infinitely. It was then a simple case of an error when typing:
} elseif(!$GLOBALS['block_loop'][$loop_position][block_name] = $block_name) {
return false;
Should have been:
} elseif($GLOBALS['block_loop'][$loop_position][block_name] != $block_name) {
return false;
Note that I had the exclamation point in the incorrect place.
This now works perfectly as I need.
I'm new to php and need some help with "GET" variables.
Here an extraction of my Code for index.php:
$array = array("section","view","sub","cat","point");
$i = 0;
$check = true;
foreach ($_GET as $position => $wert) {
if ($position != $array[$i]) {
//if GET doesnt exist in the array set check to false
$check = false;
break;
}
$i++;
}
//if GET variables exists
if ($check == true) {
if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $_GET['cat'], $_GET['point'], $point[$_GET['point']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$_GET['sub']."/".$_GET['cat']."/".$point[$_GET['point']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $_GET['cat'], $cat[$_GET['cat']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$_GET['sub']."/".$cat[$_GET['cat']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $_GET['sub'], $sub[$_GET['sub']])) {
$path = $path_dynamic.$_GET['section']."/".$_GET['view']."/".$sub[$_GET['sub']];
check($path);
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
check($path);
} else if (isset($_GET['section'], $section[$_GET['section']])) {
$path = $path_dynamic.$section[$_GET['section']];
check($path);
//if section isn't set
} else if (!isset($_GET['section'])) {
include ($path_dynamic.$section['news']);
}
} else {
echo "GET doesn't exist";
include ($path_static.$section['error']);
}
//check if GET exists
function check($path) {
if (file_exists($path)) {
echo "File imported<br />";
include ($path);
} else {
echo "GET set correct but file doens't exist";
include ('include/static/fehler.html');
}
}
Example of section.php (view, sub, cat and point is the same):
$section = array();
$section['error'] = 'fehler.html';
My problem is that if i set this link:
index.php?section=verein&view=vorstande
"vorstande" doesn't exist in my view array. So the code checks for the section "verein" and include "verein". But it should give an error.
So it seems that this code
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
is ignored and it jumps to
} else if (isset($_GET['section'], $section[$_GET['section']])) {
Also if I change my url to this:
index.php?section=vereine&view=vorstande
nothing happens. I even don't know where the code is right now.
But if I change the url to this:
index.php?section=vereine&view=vorstand
everything works fine.
So "verein" and "vorstand" is defined by me. "vereine" and "vorstande" doens't exist.
Any suggestions? Sry for comments in german. The echo only gives me a hint where the code is right now!
Link to my HP:
Edit:
- translated comments for better conversation
- deleted all "$...[$_GET['...']]" structures to show the error I will get instead.
"vorstande" doesn't exist in my view array. So the code checks for the
section "verein" and include "verein". But it should give an error.
By "give an error" you mean $check = false;?
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
If in your $view the key vorstande does not exist, this the whole condition will evaluate to false and next condition will be checked:
} else if (isset($_GET['section'], $section[$_GET['section']])) {
Edit:
Your code:
else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
check($path);
}
Your requirement:
if (!isset($view[$_GET['view']]))
check(/* something invalid to display fehler.html */ false);
What actually happens:
isset($_GET['section']) // true
isset($_GET['view']) // true
isset($view[$_GET['view']]) // FALSE
=> isset($_GET['section'], $_GET['view'], $view[$_GET['view']]) // FALSE
If the $_GET['view'] does not exist in $view, the block which would call check is not executed. If you want it to be executed regardless, simply remove the condition isset($view[$_GET['view']]):
else if (isset($_GET['section'], $_GET['view'])) {
$path = $path_dynamic.$_GET['section']."/".#$view[$_GET['view']]; // # to suppress errors from accessing
check($path);
}
If you don't like this approach, work on your cases. You have one case for section isset AND view isset AND view is valid. The next case ignores the view parameter. So if your view parameter is not valid, your code handles it like it was not set. The requirement though is to have a case for section isset AND view isset AND view is invalid:
else if (isset($_GET['section'], $_GET['view']) && !isset($view[$_GET['view']])) {
check(false);
}
This is of course pretty much redundant checking so just nest it to something like:
else if (isset($_GET['section'], $_GET['view']))
{
// section and view have been passed
if (isset($view[$_GET['view']])
// view is actually valid
$path = $path_dynamic.$_GET['section']."/".$view[$_GET['view']];
else
// view has been passed but is invalid. show fehler.html
$path = false;
check($path);
}
Alternate Example
If I understand you correctly, you have the following requirement: If the user passes a parameter section, view, sub, cat or point, you want that this value is also in your list of valid values. If it isn't, you want to display fehler.html.
We now first ensure that if the parameter is set, it is also valid:
foreach ($array as $param)
{
// example for $param == "view":
// !isset( $view[$_GET["view"]] )
if (!isset( ${$param}[$_GET[$param]] ))
{
$check = false;
break;
}
}
We then check all your combinations of parameters and build a $path
$path = false;
if ($check)
{
// your long if isset else if isset block where
// isset($_GET['view']) also implies isset($view[$_GET['view']])
// so you don't have to check for it.
// just set the $path variable with some string.
// we are going to check it later
}
If now the initial $check failed or we built an invalid $path, display fehler.html
if ($check === false || !file_exists($path))
{
// display fehler.html
}
else
include($path);
The problem is here:
} else if (isset($_GET['section'], $_GET['view'], $view[$_GET['view']])) {
Each parameter of isset must be true for the statement to return true. In your example, $_GET['section'] and $_GET['view'] are set, but $view[$_GET['view']] is not, so execution continues on the next else if line.
To fix the problem, either set $view[$_GET['view']] previously, or remove that parameter.
I have index.php page with "default" meta tags, with switch function I call e.g. single_page.php and its looks something like www.something.com/?page=single_page.
how can I overwrite meta tags from index page with meta tags from single_page.php
$conlibrary="play/pages/" ;
IF(!isset($_GET['page'])){
$page = 'deafault';
} ELSE {
$page = $_GET['page'];
$findme = '&';
$pos = strpos($page, $findme);
IF ($pos ===true) {
$data = explode("&", $data);
$dest =$conlibrary."/".$data[0].".php";
IF (file_exists($dest)) {
$page = $_GET['page'];
} ELSE {
$page = '404';
}
} ELSE {
$dest =$conlibrary."/".$page.".php";
IF (file_exists($dest)) {
$page = $_GET['page'];
} ELSE {
$page = '404';
}
}
}
include($conlibrary . $page .".php");
If you really need to modify meta tags, and depending on the specific situation, my strategy would be to give the meta tags ID attributes and then make the alterations using Javascript, as in this gist.
It doesn't work so well if the alterations need to be made before the page is sent to the browser; as PHP is not a primary language, my amateur instinct would be to simply use string variables for the "default" meta tags (rewriting the code if required) so that the included file could modify those strings as necessary.
<?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.