PHP Reference Β· String Functions
PHP urlencode() and rawurlencode() functions
Reference for PHP urlencode(), rawurlencode(), urldecode() and rawurldecode(): percent-encode text for URLs, the plus-versus-%20 difference and common mistakes.
urlencode() and rawurlencode() turn a string into a form that is safe to place inside a URL. Every byte that is not a letter, a digit or one of a few safe punctuation marks becomes a percent sign followed by two hex digits, so Γ© (two bytes in UTF-8) becomes %C3%A9. Their partners urldecode() and rawurldecode() reverse the process.
The two encoders differ in two details. urlencode() follows the application/x-www-form-urlencoded format used by HTML forms: it writes a space as + and also encodes ~. rawurlencode() follows RFC 3986: a space becomes %20 and ~ stays as it is. Use rawurlencode() for path segments and urlencode() (or http_build_query()) for query-string values.
<?php echo urlencode("a b&c=d/Γ©"); // a+b%26c%3Dd%2F%C3%A9 echo rawurlencode("a b&c=d/Γ©"); // a%20b%26c%3Dd%2F%C3%A9
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
urlencode(string $string): string rawurlencode(string $string): string urldecode(string $string): string rawurldecode(string $string): string
| Name | Description |
|---|---|
$string |
The text to encode, or the percent-encoded text to decode. |
Return value: the encoded or decoded string. None of these functions throws or returns false.
Usage notes
- Encode parts, never the whole URL. Running a full URL through
urlencode()also encodes:,/,?and=, which destroys it. Encode each value or path segment separately, then join them. urlencode()for query values,rawurlencode()for paths. A literal+in a path means a plus sign, not a space, so a path built withurlencode()can be misread.- Decoding differs too.
urldecode()turns+into a space;rawurldecode()keeps the plus. Both decode%XXsequences. - No double decoding. PHP already decodes
$_GETand$_POSTvalues before your code sees them. Callingurldecode()on them again corrupts values that contain%or+. - Bytes, not characters. Encoding works on the raw bytes, so the string should already be in the encoding the receiver expects (normally UTF-8).
- Not for HTML. Escaping for HTML output is a different job: use
htmlspecialchars(). - Many parameters at once:
http_build_query()encodes a whole array and joins it with&.