vampnerdlord vampnerdlord -3 years ago 104
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
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: 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:

// 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';
        $fileName = 'index.php';
// 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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download