Is it a bad practice to use a GET parameter (in UR

2020-02-27 18:29发布

问题:

I'm in a little argument with my boss about URLs using GET parameters without value. E.g.

http://www.example.com/?logout

I see this kind of link fairly often on the web, but of course, this doesn't mean it's a good thing. He fears that this is not standard and could lead to unexpected errors, so he'd rather like me to use something like:

http://www.example.com/?logout=yes

In my experience, I've never encountered any problem using empty parameters, and they sometimes make more sense to me (like in this case, where ?logout=no wouldn't make any sense, so the value of "logout" is irrelevant and I would only test for the presence of the parameter server-side, not for its value). (It also looks cleaner.)

However I can't find confirmation that this kind of usage is actually valid and therefore really can't cause any problem ever.

Do you have any link about this?

回答1:

RFC 2396, "Uniform Resource Identifiers (URI): Generic Syntax", §3.4, "Query Component" is the authoritative source of information on the query string, and states:

The query component is a string of information to be interpreted by the resource.

[...]

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

RFC 2616, "Hypertext Transfer Protocol -- HTTP/1.1", §3.2.2, "http URL", does not redefine this.

In short, the query string you give ("logout") is perfectly valid.



回答2:

A value is not required for the key to have any effect. It doesn't make the URL any less valid either, the URL RFC1738 does not list it as required part of the URL.

If you don't really need a value, it's just a matter of preference.

http://example.com/?logout

Is just as much a valid URL as

http://example.com/?logout=yes

All difference that it makes is that if you want to make sure that the "yes" bit was absolutely set, you can check for it's value. Like:

if(isset($_GET['logout']) && $_GET['logout'] == "yes") {
    // Only proceed if the value is explicitly set to yes

If you just want to know if the logout key was set somewhere in the URL, it would suffice to just list the key with no value assigned to it. You can then check it like this:

if(isset($_GET['logout'])) {
    // Continue regardless of what the value is set to (or if it's left empty)


回答3:

It's perfectly fine, and won't cause any error. Though, nowadays most frameworks are MVC based, so in the URL you need to mention a controller and an action, so it looks more like /users/logout (BTW, also StackOverflow uses that URL to log users out ;).

The statement that it may cause errors to me sounds like your applications manually access the raw $_GET, and I definitely think that building apps without a framework (which usually provides an MVC stack and a router/dispatcher) is the real dangerous thing here.



标签: php url get