4

I need to replace url invalid characters with something url valid then convert it back again.

This is for a search page with a url like http://my.site/search/this-is-a-search, the search form POSTS then the user redirected to the new url.

Php has functions urlencode and urldecode however these do not work at all, and leave invalid characters in my url.

Surely I don't need to reinvent the wheel here.

2
  • You might want to explain better what the workflow is. The user submits a search through a POST and is forwarded to http://my.site/search/what-the-user-has-entered? Commented Jun 11, 2010 at 5:28
  • "these do not work" is not a very meaningful description of the problem. Please provide hard examples. Commented Jun 11, 2010 at 13:11

2 Answers 2

4

For stuff like http://my.site/search/this-is-a-search (i.e., outside the query string), you should use rawurlencode and rawurldecode. These are guaranteed to be URL-safe.

However, urlencode will never generate an unsafe URL path either, since the only difference is how spaces are encoded and urlencode encodes spaces to +, which is permitted in the URL path.

From RFC 1738:

httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
hpath          = hsegment *[ "/" hsegment ]
hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
uchar          = unreserved | escape
unreserved     = alpha | digit | safe | extra
safe           = "$" | "-" | "_" | "." | "+"
Sign up to request clarification or add additional context in comments.

4 Comments

rawurlencode still leaves ' and , in the url. I have a feeling the problem is the encoding of the POST string however.
@Keyo ' and , are also allowed: extra = "!" | "*" | "'" | "(" | ")" | ","
I tracked it down to codeigniter (php framework) not allowing these characters.
@Keyo Well, you can convert them yourself to the %XX escape sequence if you wish.
2

What about rawurlencode().

http://www.php.net/manual/en/function.rawurlencode.php

echo rawurlencode('http://my.site/search/this-is-a-search');
// http%3A%2F%2Fmy.site%2Fsearch%2Fthis-is-a-search

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.