What is URL Encoding?
URL encoding (also known as percent encoding) converts characters into a format that can be safely transmitted in URLs. It replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
For example, a space becomes %20, and an ampersand (&) becomes %26.
When to Use URL Encoding
- →Creating Dynamic URLs:When building URLs with variable parameters, encode the values to ensure they're correctly interpreted.
- →Handling User Input:Always encode user-supplied data before including it in a URL to prevent injection attacks.
- →International Characters:When using non-ASCII characters (like accents or symbols) in URLs, encoding ensures they work properly.
- →Query Parameters:Encode parameter values to handle spaces, special characters, and symbols correctly.
Reserved Characters Reference
| Character | Encoded |
|---|---|
| ! | %21 |
| " | %22 |
| # | %23 |
| $ | %24 |
| % | %25 |
| & | %26 |
| ' | %27 |
| ( | %28 |
| ) | %29 |
| * | %2A |
| + | %2B |
| , | %2C |
| / | %2F |
| : | %3A |
| ; | %3B |
| = | %3D |
| ? | %3F |
| @ | %40 |
| [ | %5B |
| ] | %5D |
Security Best Practices
Always encode user input. URL encoding helps prevent injection attacks by converting potentially dangerous characters into harmless encoded strings. Never include raw user input in URLs without encoding.
- ✓Encode all user-supplied data before adding to URLs
- ✓Use server-side encoding in addition to client-side
- ✓Validate and sanitize input data before encoding
- ✓Be aware that encoding alone doesn't prevent all security issues
How URL Encoding Works
URL encoding converts unsafe ASCII characters to a "%" followed by two hexadecimal digits. The hexadecimal digits represent the character's ASCII code.
Example
"Hello World!" → "Hello%20World%21"
Space (ASCII 32) becomes %20, exclamation (ASCII 33) becomes %21
Why is this needed?
- •URLs can only use a limited set of characters
- •Some characters have special meanings in URLs (? starts query, & separates params)
- •Non-ASCII characters need encoding for proper transmission
- •Encoding ensures consistent behavior across all browsers and servers