35

I have a PHP project where I need to send a hash character (#) within the path of a URL. (http://www.example.com/parameter#23/parameter#67/index.php) I thought that urlencode would allow that, converting the hash to %23

But now I see that even the urlencoded hash forces the browser to treat everything to the right as the URL fragment (or query).

Is there a way to pass a hash through, or do I need to do a character substitution prior to urlencode?

Edit to add (Sep 19 2017):

It turns out that I was asking the wrong question. My issue wasn't with using the hash character within the path (encoding it does work), but in using mod_rewrite to convert it over to a query string. I had failed to re-encode it within the RewriteRule. I'll edit the title to match.

Here is the rewrite rule I was using:

RewriteEngine On
# convert path strings into query strings
RewriteRule "^(.*)/(.*)/hashtags.php"      /hashtags.php?parameter_1=$1&parameter_2=$2 [QSA,L]

As soon as I added the B tag, it worked correctly:

RewriteEngine On
# convert path strings into query strings
RewriteRule "^(.*)/(.*)/hashtags.php"      /hashtags.php?parameter_1=$1&parameter_2=$2 [QSA,L,B]
Mark
  • 1,129
  • 2
  • 12
  • 25
  • In what way do you use that URL? – Gumbo Feb 10 '11 at 17:30
  • I believe urlencode should change that to %23, can you provide an example code? – David Houde Feb 10 '11 at 17:33
  • I'm creating static links to dynamically created PDFs. I'm using modrewrite to pass the path elements into $_GET. They are product parrameters needed to create the PDF. Some of the products have hash tags in the product names. – Mark Feb 10 '11 at 17:34
  • 5
    The hash is a reserved character, and web browsers will treat it this way no matter what. It doesn't matter if you encode it because the interpretation will be the same. Is there another character you can use? – Jeremy Morgan Feb 10 '11 at 17:35
  • Jeremy: Yeah, after a bit more testing, I realize that it's the browser that's doing it. If I bypass the browser and just tell PHP to interpret two URLs (one with urlencode, and one without), it parses the encoded URL perfectly. I'll have to do a substitution prior to creating the URL. Thanks! – Mark Feb 10 '11 at 17:39

1 Answers1

85

Encode the Hash in the URL with %23

http://twitter.com/home?status=I+believe+in+%23love

"I believe in #love"

URL Encoding Reference: http://www.w3schools.com/tags/ref_urlencode.asp

sparkyspider
  • 13,195
  • 10
  • 89
  • 133
  • 2
    This works, surprising it took so long to be answered correctly – Benjineer Nov 25 '13 at 07:07
  • Marked this answer as correct. I wonder whether there was a change in browsers from when I first asked it. I definitely tried %23. – Mark Feb 17 '14 at 22:21
  • After six years, I revisited this and realized that Spider was correct, and that I had actually been asking the wrong question. Edited the title and the question to reflect that. Better late than never, right? – Mark Sep 19 '17 at 16:51