Thursday, August 1, 2019

note to self: less noisy CGI param checking in PHP

Insert usual sorry-not-sorry-for-using-php... there's that old Larry Wall adage how programs that wish to communicate well should "be strict in what they emit, and liberal in what they accept". One place where PHP lags Perl in this is checking for hash values when the key is missing - I find my server logs getting full of "PHP Notice:  Undefined index" when looking in $_GET or $_POST but I have fine default behaviors ready if those values aren't there.

I guess
function getval($key, $default = ''){
    return isset($_GET[$key]) ? $_GET[$key] : $default;    
}
function postval($key, $default = ''){
    return isset($_POST[$key]) ? $_POST[$key] : $default;    
}
function requestval($key, $default = ''){
    return isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;    
}
Does about as good a job as anything at checking first, in a safe way. (array_key_exists would have worked as well, I suppose...)

Random aside, and thinking of that Larry Wall quote- I remember way back when, like in the 90s, thinking it was annoying to have to check POSTs differently from GET, since CGI was a nice abstraction over either, and while the internals of how that data is passed might be very different, from the scriptwriters point of view they were kind of the same.

Now, I guess I get it. People get an intuition for what should be GET and what should be POST, so PHP's generic REQUEST (which includes cookies) is kind of an afterthought. It just feels less chaotic to understand what's channel stuff is coming in from.

No comments:

Post a Comment