Forum Moderators: coopster

Message Too Old, No Replies

Proper coding, do I need to ensure a param exists before using it?

         

csdude55

8:11 pm on Aug 10, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have code like this:

$qs = str_replace('foo=' . $_GET['foo'], '', $qs);

When $_GET['foo'] doesn't exist, though, I get a NOTICE. Which isn't a big deal, but it makes me question whether I'm following proper protocol, and if I should make adjustments in case a future release takes it more seriously.

The obvious solution would be to predeclare any of them in advance:

$_GET['foo'] ?= false;
$qs = str_replace('foo=' . $_GET['foo'], '', $qs);

but I hate to waste time and space if it's unnecessary. Or if there's a better way.

csdude55

9:08 pm on Aug 10, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$_GET['foo'] ?= false is supposed to have two question marks, but the system keeps stripping it down to one. Sorry about that.

ronin

11:05 pm on Aug 15, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In this instance I'd be tempted to use a conditional block which runs only if the named parameter exists in the query string:


if (isset($_GET['foo'])) {
$qs = str_replace('foo='.$_GET['foo'], '', $qs);
}

robzilla

7:05 am on Aug 16, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Agree with ronin. You could also write it like so:
$qs = isset($_GET['foo']) ? str_replace('foo='.$_GET['foo'], '', $qs) : $qs;

brotherhood of LAN

9:40 pm on Aug 16, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Totally depends on your program flow IMO. I wouldn't rely on ignoring notices for it to be good code, either your code deals with it or expect the unexpected.

I always check for the existence of things and since PHP can typecast things into any manner of types of variable, I check their type also.

Depends on context also, if it's an admin only kind of thing, be a bit looser with the validation. If it's user submitted, check it exists, its type and its contents if that's important.

You can abstract this kind of logic into one class and just do it that way.