I am somewhat a newby at PHP ... so what im trying to do is to get the the page using the following code
<?php include $_GET['topic']; ?>
to get the url like this http://ulixtxteditor.org/entities/helpCentre?topic=credits that much works great for me however if no page is found i would like to use the else statement to display an error instead of a blank page. What should I do? ex: http://ulixtxteditor.org/entities/helpCentre?topic= so this part would display an error?
<?php if(isset){include $_GET['topic'];} else {echo "error"} ?>
I tried this but it wont work.
Use something like this:
<?php
// In case topic parameter wasn't provided you will have fallback.
$topic = isset($_GET['topic']) ? $_GET['topic'] : '';
// Now you can check topic and have valid file name.
switch ($topic) {
case 'credits':
$fileName = 'credits.php';
break;
default:
$fileName = 'index.php';
break;
}
// Now it is possible safely include file.
include __DIR__ . DIRECTORY_SEPARATOR . $fileName;
Using $_GET['topic']
directly in include
or require
construction is unsafe because you vulnerable to "Directory traversal attack". Moreover you always must validate input parameters with purpose avoid include in php script css files etc...
This is a fairly common way of implementing a simple junction box/router. Use a switch statement.
$topic = isset($_GET['topic']) ? $_GET['topic'] : '';
switch ($page) {
case 'credit':
case 'otherpage':
case 'otherpage2':
require_once(dirname(__FILE__) . '/' . $page . '.php');
break;
default
require_once(dirname(__FILE__) . '/' . 'default.php');
}
You whitelist your pages/topics by adding a case statement at the top for each, and anything that doesn't match or have a page is processed by loading the default page.
In this example, I assume all the topic pages are in the same directory as this script (typically named index.php).
<?php include $_GET['topic']; ?>
Don't do that. It creates a massive and easily-exploited security vulnerability.
For example:
?topic=index.php
-- creates an infinite loop
?topic=/etc/passwd
-- displays sensitive data from the server
?topic=/proc/self/environ
-- executes code from the process environment. This will frequently include user-controlled data like the values of HTTP headers, allowing for remote code execution.
Your site will be exploited if you implement this. There are numerous bots which scan public web sites for this vulnerability, many of which will attempt to exploit it automatically upon detection.
If you want to include a file based on the value of a GET variable, use switch($_GET['topic')
to define the acceptable values of that variable. This will also allow you to implement error handling as a default:
clause.