I have a switch case to display my php pages with id's like this:
<?php
$id = 1;
if(isset($_GET['id'])){
$id = $_GET['id'];
}
switch ($id) {
case 1: require_once 'home.php';
break;
case 2: require_once 'courseInfo.php';
break;
case 3: require_once 'aboutUs.html';
break;
case 4: require_once 'contacts.html';
break;
case 5: require_once 'accountDashboard.php';
break;
case 6: require_once 'accountCourses.php';
break;
case 7 : require_once 'studentLogin.php';
break;
case 8 : require_once 'applicationForm.php';
break;
case 9: require_once 'accountFiles.php';
break;
case 10: require_once 'accountCursoAulas.php';
break;
case 11: require_once 'event.php';
break;
case 12: require_once 'allEvents.php';
break;
default: require_once 'home.php';
break;
}
?>
I have an error page already and want to display it when a user types an id in the URL that is not in the switch case. I assume this is pretty easy but I can't seem to think or find it anywhere.
CodePudding user response:
And that's where the default case comes in, you could go like
<?php
$id = 1;
if(isset($_GET['id'])){
$id = $_GET['id'];
}
switch ($id) {
case 1: require_once 'home.php';
break;
case 2: require_once 'courseInfo.php';
break;
case 3: require_once 'aboutUs.html';
break;
case 4: require_once 'contacts.html';
break;
case 5: require_once 'accountDashboard.php';
break;
case 6: require_once 'accountCourses.php';
break;
case 7 : require_once 'studentLogin.php';
break;
case 8 : require_once 'applicationForm.php';
break;
case 9: require_once 'accountFiles.php';
break;
case 10: require_once 'accountCursoAulas.php';
break;
case 11: require_once 'event.php';
break;
case 12: require_once 'allEvents.php';
break;
default: require_once 'errorPage.php'; //Since id didn't match any value
break;
}
?>
Or you could just validate id if you know the range of values
<?php
$id = 1;
if(isset($_GET['id'])){
$id = $_GET['id'];
}
if($id < 1 || $id > 12){
require_once 'errorPage.php';
}else{
switch ($id) {
case 1: require_once 'home.php';
break;
case 2: require_once 'courseInfo.php';
break;
case 3: require_once 'aboutUs.html';
break;
case 4: require_once 'contacts.html';
break;
case 5: require_once 'accountDashboard.php';
break;
case 6: require_once 'accountCourses.php';
break;
case 7 : require_once 'studentLogin.php';
break;
case 8 : require_once 'applicationForm.php';
break;
case 9: require_once 'accountFiles.php';
break;
case 10: require_once 'accountCursoAulas.php';
break;
case 11: require_once 'event.php';
break;
case 12: require_once 'allEvents.php';
break;
default: require_once 'home.php';
break;
}
}
?>