lilo346
lilo346

Reputation: 21

Why am I getting an Undefined Index Error?

<?php  
$p = $_GET['page'];

$page = $p.".php";

if(file_exists($page))
    include($page);
elseif($p=="")
    include("home.php");
else
    include("404.php");

?>

This block of code is giving me an Undefined Index error for the $page variable, i tried doing this......

<?php  
$p = $_GET['page'];

if(isset($page)){$page = $p.".php";}

if(file_exists($page))
    include($page);
elseif($p=="")
    include("home.php");
else
    include("404.php");

?>

but this did nothing. I'm still a novice at PHP and I'm not sure what I need to do to fix this. Any suggestions?

EDIT: For everyone wanting the url: http://memphislinuxboy.tk/ ALso, for those of you wanting to know about security, the included file must be .PHP

Upvotes: 1

Views: 866

Answers (3)

cmorrissey
cmorrissey

Reputation: 8583

$_GET['page'] is not set in your code your url needs to contain ?page=somepage

<?php  

    $page = (isset($_GET['page']) ? $_GET['page'] : 'home') . '.php';

    if(file_exists($page)){
        include($page);
    } else {
        include("404.php");
    }

?>

Upvotes: 0

castis
castis

Reputation: 8223

the line $p = $_GET['page']; is throwing the error.

You're attempting to access an array element that has not yet been set.

Check to make sure the value exists before using it.

if (isset($_GET['page']))
{
    $page = $_GET['page'];
}
else
{
    // this is the page they'll have if they havnt specified one
    $page = 1;
}

Upvotes: 0

Jamie Taylor
Jamie Taylor

Reputation: 4765

I'd imagine $_GET['page']; isn't set, check the URL going in to make sure it contains "page=" at some point.

You can fix this with

if(isset($_GET['page']) {
    //your code
}

Off topic:

if(file_exists($page))
    include($page);

You're attempting to include a file specified by the client. This could be a serious security flaw if not handled correctly. It's probably best to check against a list of known (good) files.

Upvotes: 3

Related Questions