25

My question is related to this one. except that my question is more sepcific as it is about whether a hyphen can be used in a query string parameter value.

I am parsing $_SERVER['QUERY_STRING'] with PHP. I would like to know whether it is syntactically correct to use hyphens in query string values such as in the following case, or whether hyphens must be escaped in the browser URL. What about underscores?

http://example.com/?q1=query-string-value-one&q2=query-string-value-two

According to this document hyphens should be OK in all standards-compliant browsers, but I wanted to double check.

Thanks.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
John Sonderson
  • 3,238
  • 6
  • 31
  • 45
  • 5
    [Well, have you given a try to see if it works?](http://meta.stackoverflow.com/questions/289336/is-it-okay-to-downvote-questions-asking-if-some-code-could-work-but-not-actually) – D4V1D Sep 02 '15 at 09:03
  • 4
    Well, I don't just want to know if it works. I need to know whether it is legal according to RFC specs. – John Sonderson Sep 02 '15 at 09:05
  • 3
    yes `hyphens` can be used . only characters can reliably use for the actual name parts of a URL are a-z, A-Z, 0-9, -, ., _, and ~. – Bender Sep 02 '15 at 09:09
  • 2
    possible duplicate of [Safe characters for friendly url](http://stackoverflow.com/questions/695438/safe-characters-for-friendly-url) – Hans Z. Sep 02 '15 at 09:17
  • 1
    I don't think this is a duplicate @HansZ. The question you link to is concerned about legal characters in a url _in general_. This question is concerned with how query parameter _names_ are parsed. – seebiscuit Apr 06 '20 at 14:57
  • Just in values, or can they be used in keys as well? – s3c Aug 27 '21 at 13:45

2 Answers2

29

You are talking about query string parameters which must be encoded using urlencode function:

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

According to the documentation - does not require encoding.

benomatis
  • 5,536
  • 7
  • 36
  • 59
Salman A
  • 262,204
  • 82
  • 430
  • 521
16

Yes

Hyphens can be used for query string parameter names

Tomi
  • 3,370
  • 1
  • 16
  • 26