Illscha Illscha - 4 months ago 12
PHP Question

PHP Getting error for $page = $_GET['page'];

This is my entire code. Shared to you.

This is my error:

Notice: Undefined index: page in /export/home/dynamic/index.php on line 20


I can't seem to figure out why I keep getting this error. It is not the first time, I've suspected that it is the array but I don't know what to do with it.

It's suppose to make a dynamic change page to my website.
I've had errors before where I make a global varible like
$page = $_GET['page'];


I am open to any kind of answer and I am greatful to every single on of them.

<!DOCTYPE html>
<html>
<head>
<title>Website</title>
</head>
<body>
<header>Header<br />
<nav>
<a href="index.php?page=index">INDEX</a>
<a href="index.php?page=page1">Startsida</a>
<a href="index.php?page=page2">Anteckningar</a>
<a href="index.php?page=page3">Kontakt</a>
<!-- <a href="index.php?page=faq">FAQ</a> -->
</nav></header>

<div id="content">
<?php

// Place the value from ?page=value in the URL to the variable $page.
$page = $_GET['page'];

// Create an array of the only pages allowed.
$pageArray = array(
'index',
'page1',
'page2',
'page3',
'faq'
);

// If there is no page set, include the default main page.

if (!$page) {
include('pages/index.php');
}

// Is $page in the array?
$inArray = in_array($page, $pageArray);

// If so, include it, if not, emit error.
if ($inArray == true) {
include('pages/'. $page .'.php');
}else {
echo 'Umm tisk tisk. You should not be messing with things.';
}
?>
</div>

<footer>Footer</footer>

</body>
</html>


IT IS SOLVED!
Thanks to hek2mgl my code now works properly.

I want to thank the rest for submitting your answers to my problem. I owe you guys.

Answer

You need to check if page was transmitted via GET vars:

if(isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    // set proper default value if it was not set
    $page = 'index';
}

In the next step you need to check if $page contains a proper value:

if(!in_array($page, $pages)) {
    die('page was not found');
}
Comments