HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Is this PHP code snippet safe?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thissnippetphpsafecode

Problem

Mostly asking for critiques of vulnerability. Am I using any functions or methods that are unsafe?



This is code that checks if the section is in the array and then sets it as such, but hardwires it back to default if it's not valid.

Solution

Is it safe? Yes, it will currently do the right thing.

One of the features that plays in to best practice though, is how future proof it is. Over time, code gets edited, changed, etc. What you want is to make the code 'fail safe' in the future too. What if someone comments out the second line, you end up with a problem.

A better way to write your code would be to set the default, and only change it if the input is valid:

Code Snippets

<?php
$menu = array( "page1","page2","page3" );

$section = "page1";
$input = $_GET['section'];
if ( isset( $input ) && in_array( $input, $menu ) ) {
    $section = $input;
}

?>

Context

StackExchange Code Review Q#54847, answer score: 6

Revisions (0)

No revisions yet.