59

If I have a variable to pass through a URL and it has a question mark in it, do I just need to escape the question mark?

If not, how can I make sure it passes through like it's supposed to?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
townie
  • 767
  • 2
  • 8
  • 12
  • @StefanH Ok. My url will be something like `site.com?var1=apples&var2=newsite.com?w.newsite.com&var3=stuff` I didn't know if that would make things act weird. – townie Feb 20 '12 at 06:34
  • I'm sorry - I misread the question - My answer was wrong. You would definitely want to encode that :) – Stefan H Feb 20 '12 at 06:43

3 Answers3

71

A question mark URL encodes as %3F. But you should use a proper encoder for the whole thing rather than manually encoding a character.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
12

According to my experience of trying to make a JavaScript search engine that links to Google, just replace the question marks with %3F.

A URL reads the first two characters on the right of a % as hexadecimal format.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ElectroBit
  • 1,152
  • 11
  • 16
8

Here's a full list of URL encoding characters. If you're using PHP for a server-side language, you can use something like...

$nice_url = urlencode("http://your.old.url");

Other languages will have similar functions build in (or you can find one online). This will take care of your question mark (and other URL issues).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DorkRawk
  • 732
  • 2
  • 6
  • 21
  • 5
    You should encode path segments individually, rather than encoding the entire URL. Otherwise, you will also encode the colon after the scheme, the dots in the FQDN and the slashes that separate path segments. Plase take a look at https://tools.ietf.org/html/rfc3986 – cmoran92 Mar 25 '17 at 05:41
  • Wrong (or a misunderstanding). If you want to have a URL parameter that resembles a URL, the whole parameter value (i.e. the whole URL) must be URL encoded, including colons, slashes, etc. So you pass the whole URL through urlencode() and then use the result literally as a parameter value inside the query string. The query string then looks like this: var1=apples&var2=https%3A%2F%2Fwww.google.com%2F%3Fq%3Dwhatever&var3=stuff – thomas.schuerger Aug 11 '23 at 15:38