What security risks should be considered when using $_GET and switch to generate dynamic content in PHP?
When using $_GET and switch to generate dynamic content in PHP, a major security risk to consider is the potential for injection attacks. To mitigate this risk, it is crucial to validate and sanitize user input before using it in a switch statement to prevent malicious code execution.
// Validate and sanitize the input from $_GET
$page = isset($_GET['page']) ? $_GET['page'] : 'default';
$allowed_pages = ['home', 'about', 'contact'];
// Check if the requested page is in the allowed_pages array
if (in_array($page, $allowed_pages)) {
// Use a switch statement to determine the content to display
switch ($page) {
case 'home':
echo 'Welcome to the homepage!';
break;
case 'about':
echo 'Learn more about us.';
break;
case 'contact':
echo 'Contact us for more information.';
break;
default:
echo 'Page not found.';
break;
}
} else {
echo 'Invalid page requested.';
}
Keywords
Related Questions
- What are some potential pitfalls of using PHP for template classes?
- Is it feasible to create a comprehensive exclusion list to improve the accuracy of sentence extraction in PHP, or would it lead to performance issues?
- What are the differences between executing PHP code in a browser versus in the command line?