Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Using PHP GET and POST variables efficiently

Stanislav KhromovStanislav Khromov

Most PHP frameworks nowadays have helper functions for HTTP GET/POST variables ($_GET and $_POST).

But sometimes, you may still have to use the raw values, which means you have to check if the array key with the variable you want exists before assigning it, maybe something like this:

if(isset($_GET['mykey']))
    $key = $_GET['mykey']
else
    $key = '';

Pretty long… Let’s try the shorthand if/else syntax! (aka. ternary operator)

$key = isset($_GET['mykey']) ? $_GET['mykey'] : '';

That’s better! But it’s still too long. Can we make it even shorter? Let’s try a helper function!

function get($key,  $default_value = '')
{
    return isset($_GET[$key]) ? $_GET[$key] : $default_value;
}

Awesome! Now we can simply do:

$key = get('mykey');

We can also conveniently pass a default value as the second parameter if the value isn’t set in the $_GET array:

$key = get('mykey', 'hello'); //Returns "hello" if mykey isn't set.

Great, let’s finish this up by making a post() function as well! While we’re at it, let’s put these functions in a class so they don’t risk conflicting with anything else.

class Helper
{
    static function get($key,  $default_value = '')
    {
        return isset($_GET[$key]) ? $_GET[$key] : $default_value;
    }

    static function post($key,  $default_value = '')
    {
        return isset($_POST[$key]) ? $_POST[$key] : $default_value;
    }
}

//Let's try it!
$key1 = Helper::get('key1');
$key2 = Helper::post('key2');
PHP

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 2