One way to pass data to a web page is via the URL query string. The data must be properly encoded – urlencode() and rawurlencode() in PHP do this.
The PHP urlencode() function URL encodes strings in PHP and is widely used, but it is not the best tool for the job. rawurlencode() is the modern replacement for urlencode() – though you may need to use the older urlencode() for compatibility if you’re working on older code.
- urlencode() will return a string variable containing the URL encoded value
- Non-alpha-numeric characters (other than dashes, underscores, and periods) will be replaced with a percent (%) symbol and a hexadecimal digit pair
- Spaces will be replaced with a plus (+) symbol
- $string is the string or string variable to be encoded
Below, urlencode() is used to encode a string for safe use in a URL:
$encoded = urlencode('to be, or not to be?'); echo $encoded;
Here’s the output:
You can see that the spaces have all been replaced with plus symbols (+) and non-alphanumeric characters replaced with a percent (%) symbol and two hexadecimal characters.
Decoding with urldecode()
urlencode() can be reversed with urldecode, which returns the original string.
$encoded = urlencode('to be, or not to be?'); echo $encoded; echo "\n"; $decoded = urldecode($encoded); echo $decoded;
Which will return:
to be, or not to be?
rawurlencode() – The Superior PHP URL Encoder
rawurlencode() is the modern replacement for urlencode() and should be used instead unless legacy compatibility is required. The syntax is the same:
- It works the same as urlencode()
- However, it uses a better encoding system
- For example, rather than replacing spaces with a plus symbol, it replaces them with a percent sign and hexadecimal character pair, reducing the chances of a value containing spaces and plusses being incorrectly parsed
rawurlencode() and rawurldecode() Example
In the example below, the same string as used in the above example is encoded using rawurlencode():
$encoded = rawurlencode('to be, or not to be?'); echo $encoded; echo "\n"; $decoded = rawurldecode($encoded); echo $decoded;
Which will output the encoded and decoded strings:
to%20be%2C%20or%20not%20to%20be%3F to be, or not to be?
The string is encoded in a way that is less likely to be parsed incorrectly due to using unencoded symbols as separators.
For more information and examples on using rawurlencode(), check out the official PHP documentation.