1

am fiddling around with a search form i've managed to string together which works. In total there is a possibility to input 28 values including checkbox's and selection options. So i have this code repeated 28 times with different variables, is there a shorter way to do this, it looks so nasty in my code which leads me to believe am doing something very wrong. Here is an example of my code:

            $search_shop_name = '';

            if(isset($_GET['search_shop_name'])) {
            $search_shop_name = $_GET['search_shop_name']; 
    }               
    else {
        $search_shop_name = '';
    }   

That is just 1 piece of code for one input, imagine how long and sloppy this code is. Any advice would be appreciated. thanks

2 Answers 2

3

Use filter_input()[docs]. It will shorten your code to a single line:

$search_shop_name = filter_input('search_shot_name', INPUT_GET);

Or do something like this:

// put your default values here
$defaults = array(
    'search_shop_name' => '',
    'other_value' => '',
    ...
);

// merge $_GET in default values
$input = array_merge($defaults, $_GET); // or $_GET + $defaults

// you are done
$search_shop_name = $input['search_shop_name'];
Sign up to request clarification or add additional context in comments.

5 Comments

the second answer worked Perfectly, thanks so much. i must read up on this array_merge. Code looks alot tidier now.
Hi, ive been reading about injection and fiddling with, strip_tags, strip_slashes, mysql_real_escape and htmlspecialchars. But enter a element: <h1>, the H1 takes effect and breaks the site. Am trying to prevent tags from being inserted into the input box. I have considered a large number of options for a select menu to ensure the user doesn't type in tags.
Just use htmlspecialchars() when you echo a variable. Don't filter input. Escape output. Just do echo htmlspecialchar($variable).
i've input <h1> to test this and i returns: &lt;h1&gt; I have read that i MUST escape data users enter. Are there any websites or programmes to show my websites vunerabilities rather than putting it online to get taken apart in no time ?
That's wrong, you must only escape data you output. Not the input.
1

Instead of using all those conditionals, you could simply do:

$search_shop_name = $_GET['search_shop_name']; 

If the $_GET value isn't set, then $search_shop_name will be an empty string.

2 Comments

If it isn't set, it'll emit an E_NOTICE. I find it a good habit to write code that doesn't do that.
This triggers errors if $_GET['search_shop_name'] is not set. I believe this is what OP tries to avoid by using isset().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.