I would like to use this concept on my webshop, but how can I send variables through?
(You know index.php? Page = test & variable = 22 // variable does not work)
$page = isset($_GET['Page'])? trim(strtolower($_GET['Page'])) :"front";
$allowedPages = array(
'front' => './include/webshop_frontshop.php',
'logon' => './include/webshop_tjek_login.php',
'test' => './include/webshop_testside.php'
);
include( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages["front"] );
This link works fine!: nywebshop.php?Page=test
This link does not work (says the page does not exist): nywebsite.php?Page=test&item=5
Possible errors:
1) You use spaces in URL (in exemple you did)
2) In php you use $_GET['side'] - not $_GET['Page'] or $_GET['variable']
3) If you want to save variables in all pages after sending, you can use sessions:
$_SESSION['get_saved_param__Page'] = $_GET['Page'];
And it will be good to use standart
if {
// code
} else {
// code
}
As it much easier to read and you will spend most of the time in coding at reading your scripts, not writing.
Related
I'm trying to setup a page that pulls just a part of the URL but I can't even get it to echo on my page.
Since I code in PHP, I prefer dynamic pages, so my urls usually have "index.php?page=whatever"
I need the "whatever" part only.
Can someone help me. This is what I have so far, but like I said, I can't even get it to echo.
$suburl = substr($_SERVER["HTTP_HOST"],strrpos($_SERVER["REQUEST_URI"],"/")+1);
and to echo it, I have this, of course:
echo "$suburl";
If you need to get the value of the page parameter, simply use the $_GET global variable to access the value.
$page = $_GET['page']; // output => whatever
your url is index.php?page=whatever and you want to get the whatever from it
if the part is after ? ( abc.com/xyz.php?......) , you can use $_GET['name']
for your url index.php?page=whatever
use :
$parameter= $_GET['page']; //( value of $parameter will be whatever )
for your url index.php?page=whatever&no=28
use :
$parameter1= $_GET['page']; //( value of $parameter1 will be whatever )
$parameter2= $_GET['no']; //( value of $parameter2 will be 28 )
please before using the parameters received by $_GET , please sanitize it, or you may find trouble of malicious script /code injection
for url : index.php?page=whatever&no=28
like :
if(preg_match("/^[0-9]*$/", $_GET['no'])) {
$parameter2= $_GET['no'];
}
it will check, if GET parameter no is a digit (contains 0 to 9 numbers only), then only save it in $parameter2 variable.
this is just an example, do your checking and validation as per your requirement.
You can use basic PHP function parse_url for example:
<?php
$url = 'http://site.my/index.php?page=whatever';
$query = parse_url($url, PHP_URL_QUERY);
var_dump(explode('=', $query));
Working code example here: PHPize.online
Before I start, I am completely new to PHP. This is probably a stupid error and I am probably doing this in the worst way possible.
I have this code:
<?php
if (!isset($_GET['p'])) {
$url .= '?p=home';
header('Location:' . $url);
exit;
}
elseif (!isset($_GET['sp'])) {
header("Location: ".$_SERVER['REQUEST_URI'].'&sp=index.php';);
die();
}
include('/Page/' . htmlspecialchars($_GET["p"]) . '/' . htmlspecialchars($_GET["sp"]));
?>
Basically the url format is www.example.com/?p=PAGE&sp=SUBPAGE.php
The internal format from this will be /Page/PAGE/SUBPAGE.php
Reasons:
Each 'Post' will have it's own folder for it's resources. (?p=) Then they can put anything within their folder and link to it with the SUBPAGE (&sp=).
This keeps everything organised and stops any internal linking to anywhere but the /page/ area.
What's wrong:
If there is no Page (p) set I need to add ?p=home as the default and if their is no SubPage (sp) set I need to add &sp=index.php by default.
If there is no Page then the SubPage will be reset to default.
If you are on a page www.example.com/?p=blog then it will add the subpage without removing the page (?p=blog to ?p=blog&sp=index.php)
However if there is no page then the subpage will be reset to default.
The question:
How can I come about this?
Thank you, in advance.
I would approach the situation differently.
Set up some variables, for page and inner page with the default values and only re-assign them if the $_GET params are set
$page = 'home';
$inner_page = 'index.php';
if( isset( $_GET['p'] ) )
{
$page = htmlspecialchars( $_GET['p'] );
}
if( isset( $_GET['sp'] ) )
{
$inner_page = htmlspecialchars( $_GET['sp'] );
}
include $_SERVER['DOCUMENT_ROOT'] . '/Page/' . $page . '/' . $inner_page;
I've added $_SERVER['DOCUMENT_ROOT'] in too because if you use /Page then it is an absolute path, probably not what you were expecting, so prepending $_SERVER['DOCUMENT_ROOT'] ensures you're looking at the path inside your web directory.
Something else worth noting; Don't assume the data is good, people could try manipulate the files that are included.
http://your.domain/index.php?p=../../../../../&sp=passwd
So it would be worth trying to sanitize the data first.
Your current code has a big security flaw.
One of the most important rule when you write an app, never trust data coming from client. Always assume, they will send you wrong or bogus data.
I would recommend you to create a configuration file defining what are the allowed routes.
By executing the following line, you just allowed anyone to access any file that would be readable by your webserver.
include('/Page/' . htmlspecialchars($_GET["p"]) . '/' . htmlspecialchars($_GET["sp"]));
What happens If you sent a valid value for $_GET['p'] and this for $_GET['sp'] :
"/../../../../../../../../../../../etc/apache2/httpd.conf"
In this example, it will output your apache configuration file (assuming that this is the right path, if not an hacker can just keep trying path until he finds it).
To avoid this, you have two solutions.
1# Quick fix - You can sanitize & filter $_GET['p'] and $_GET['sp'] to ensure that you are not getting something '/../'. Make sure to add at least a file_exists before to avoid getting unwanted warning messages.
2# More elegant fix - You can create a configuration file that would contain the routes that you are accepting. If you are using a framework, there is a very high chance that you have a routing class or a routing module that you can just use. Otherwise, if you feel like implementing your own basic routing mechanism, you could do something as simple as in your case :
<?php
/**
* Defines the different routes for the web app
* #file : config.routes.php
*/
return array(
'page1' => array(
'index.php',
'subpage2.php',
'subpage3.php',
),
);
Then, your code you would check if the $_GET['p'] and $_GET['sp'] are allowed values or not.
<?php
// Load config file containing allowed routes
$allowedRoutes = require(__DIR__ . '/config.routes.php');
$defaultPage = 'home';
$defaultSubPage = 'index.php';
$page = isset($_GET['p']) ? $_GET['p'] : defaultPage;
$subPage = isset($_GET['sp']) ? $_GET['sp'] : $defaultSubPage;
// If it is an invalid route, then reset values to default
if (!isset($allowedRoutes[$page][$subPage]))
{
$page = $defaultPage;
$subPage = $defaultSubPage;
}
include $_SERVER['DOCUMENT_ROOT'] . '/Page/' . $page . '/' . $subPage;
I currently have the following code (which works from what I can tell so far)
session_start();
if(!is_array($_SESSION['page'])) {
$_SESSION['page']=array();
}
$_SESSION['page'][]=$_SERVER['REQUEST_URI'];
$entry=reset($_SESSION['page']);
$exit=end($_SESSION['page']);
Is this the best way to accomplish tracking of entry and exit pages with PHP?
Edit:
This (from #T0xicCode) appears to be a better option:
session_start();
if(!is_array($_SESSION['page'])) {
$_SESSION['page'] = array('entry' => $_SERVER['REQUEST_URI']);
}
$_SESSION['page']['exit'] = $_SERVER['REQUEST_URI'];
$entry = $_SESSION['page']['entry'];
$exit = $_SESSION['page']['exit'];
I'd suggest using something like google analytics, but if you want a DIY, pure php solution, something like the following should work. It doesn't track the pages in the middle, which your original solution does.
session_start();
if(!in_array('page', $_SESSION) || !is_array($_SESSION['page'])) {
$_SESSION['page'] = array('entry' => $_SERVER['REQUEST_URI']);
}
$_SESSION['page']['exit'] = $_SERVER['REQUEST_URI'];
$entry = $_SESSION['page']['entry'];
$exit = $_SESSION['page']['exit'];
You'll also have to determine how often you'll purge old sessions. If I come back after 2 weeks, is it a new browsing session, or is it the continuation of the old one?
I have a simple list of orders which a user can filter by status (open,dispatched,closed). The filter dropdown triggers a post to the server and sends the filter value through. Orders are listed out 10 to a page with pagination links for any results greater than 10. Problem is when I click the pagination links to view the next page of results the filter value in the post is lost.
public function filter_orders() {
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$filter = $this->input->post('order_status_filter');
$config = array();
$config["base_url"] = base_url() . "control/orders/filter_orders";
$config["per_page"] = 10;
$config['next_link'] = 'Next';
$config["uri_segment"] = 4;
$config['total_rows'] = $this->model_order->get_all_orders_count($this->input->post('order_status_filter'));
}
How can I make the pagination and filter work together. I've thought about injecting a query string in to the pagination links but it doesn't seem like a great solution.
The answer is very simple, use $_GET. You can also use URI segments.
i.e, index.php/cars/list/5/name-asc/price-desc'
The main reason you'll want to use $_GET is so you can link other users so they see the same result set you see. I'm sure users of your web app will want this functionality if you can imagine them linking stuff to each other.
That said, it would be ok to ALSO store the filters in the session so that if the user navigates away from the result set and then goes back, everything isn't reset.
Your best bet is to start a session and store the POST data in the session. In places in your code where you check to see if the user has sent POST data, you can check for session data (if POST is empty).
In other words, check for POST data (as you already do). If you got POST data, store it in the session. If a page has no POST data, check to see if you have session data. If you do, proceed as if it was POSTed. If you have both, overwrite the session with POST. You'll want to use new data your user sent you to overwrite older data they previously sent.
You either put everything in $_GET or if the data is sensible, put it in $_SESSION. Then it travels between pages.
In your case there seem to be no reason to put your filter data anywhere else than in $_GET.
A query string does seem the best solution. You could store it in the session or in cookies as well, but it makes sense to also store it in the query string.
Store it in cookies or the session if you want to remember the user's choice. Which seems like a friendly solution. It allows the user to keep their settings for a next visit, or for another page.
Store it in the query string, because going to 'page 2' doesn't tell you anything if you don't know about filters, page size or sorting. So if a user wants to bookmark page 2 or send it by e-mail, let them be able to send a complete link that contains this meta information.
Long story short: Store it in both.
maybe its not a right answer but, give it a try
<?php
// example url
$url = "index.php?page=6&filter1=value1&filter2=value2";
// to get the current url
//$url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
// change the page to 3 without changing any other values
echo url_change_index( $url, "page", 3 );
// will output "index.php?page=3&filter1=value1&filter2=value2"
// remove page index from url
echo url_change_index( $url, "page" );
// will output "index.php?filter1=value1&filter2=value2"
// the function
function url_change_index( $url, $name = null, $value = null ) {
$query = parse_url( $url, PHP_URL_QUERY );
$filter = str_replace( $query, "", $url );
parse_str( $query, $parsed );
$parsed = ( !isset( $parsed ) || !is_array( $parsed ) ) ? array() : $parsed;
if ( empty( $value ) ) {
unset( $parsed[$name] );
}
else {
$parsed[$name] = $value;
}
return $filter.http_build_query( $parsed );
}
?>
I want to use the array function of PHP to translate a website. I have created PHP files with arrays in them for all the text to be translated.
<?php
//ESPANOL
$lang = array(
'work' => 'Trabajo'
'packaging' => 'Empaque'
);
And then I am calling them inside my nav.php file, and will in the content section too.
<?php include('includes/languages/es.php'); ?>
<?php echo $lang['work']; ?>
All pretty straight forward.
What I want to know is how to switch between these array files without editing the HTML, so that I don't have to link to another 'index_es.php' etc. I understand that the link would be something like this, but I don't know how this is going to work.
English
I'm guessing I need to include another file that includes the language files and then the link can choose from them but I don't know what the code would be for this.
Would it involve including a 'lang_directory' above the link and then somehow including from there??
**Also I would like to avoid using Zend/Gettext translation becuase I want to learn this inside out.
You can make another dimension containing the target language. Then pass a GET parameter to select that language. If the language isn't recognized you can fallback to English. Here's a sample.
$languages = array(
'en' => array(
'work' => 'work',
'packaging' => 'packaging'
),
'es' => array(
'work' => 'Trabajo',
'packaging' => 'Empaque'
),
);
// default language to use when the requested isn't found
$defaultLanguage = 'en';
// language requested via GET
$requested = $_GET['locale'];
// use the requested language if it exists, otherwise the default language
$language = isset($languages[$requested]) ? $requested : $defaultLanguage;
// our translations
$translation = $languages[$language];
// "work" translated based on the language
echo $translation['work'];
And the link for Español would look like this.
index.php?locale=es
I'd keep your array system, correct the links into something like index.php?lang=en and then include your file depending on the lang parameter:
if ( isset($_GET['lang']) && file_exists('includes/languages/'.$_GET['lang'].'.php') ){
include_once('includes/languages/'.$_GET['lang'].'.php');
}
And if you want to keep the language parameter in your session, do something like this:
if ( isset($_GET['lang']) && file_exists('includes/languages/'.$_GET['lang'].'.php') ){
$_SESSION['lang'] = $_GET['lang'];
}
if ( !isset($_SESSION['lang']) ){
// Default language
$_SESSION['lang'] = 'en';
}
include_once('includes/languages/'.$_SESSION['lang'].'.php');
One way to do this is by using sessions.
Make a lang.php file that will be used to change between languages.
<?php
//Start session
session_start();
//Do we get a lang variable
if (isset($_GET['lang'])) {
//Make sure we only get the lang filename
$lang = basename($_GET['lang']);
//If the file exists, then save it to session
if (file_exists('includes/languages/' . $lang . '.php'))
$_SESSION['lang'] = $lang;
}
//If the client were refered here (via hyperlink) send them back
if (isset($_SERVER['HTTP_REFERER']))
header('location: ' + $_SERVER['HTTP_REFERER']);
?>
In the header of the files you want multiple languages, insert.
<?php
//Start session
session_start();
//Default language
$lang = 'english';
//If the client have set a language, use that instead
if (isset($_SESSION['lang']))
$lang = $_SESSION['lang'];
//Load language file
include('includes/languages/' . $lang . '.php');
?>
The links to change language will then be like this:
Español|English
Out can also take the code from the lang.php file and put in a included file that will be loaded before the inclusion of language file and remove the HTTP_REFERER redirection.
The links to change language will then be like this:
Español|English