vampnerdlord vampnerdlord - 1 month ago 11
PHP Question

php if include _get else display an error

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.

Answer Source

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...