URL Encode in PHP — Free Online Tool + Code Examples
Learn how to URL encode strings in PHP using urlencode() and rawurlencode(). Free online URL encoder with PHP code examples.
How to URL Encode in PHP
PHP provides two URL encoding functions: urlencode() which encodes spaces as + (for form data), and rawurlencode() which encodes spaces as %20 (RFC 3986 compliant). For most modern web applications, rawurlencode() is the recommended choice.
urlencode() and rawurlencode() Examples
<?php
// Basic encoding
$text = 'hello world & goodbye';
echo urlencode($text); // hello+world+%26+goodbye
echo rawurlencode($text); // hello%20world%20%26%20goodbye
// Build URL with encoded parameters
$params = [
'q' => 'search term with spaces',
'lang' => 'en',
'page' => 1,
];
$query = http_build_query($params);
echo \"https://api.example.com/search?{$query}\";
// https://api.example.com/search?q=search+term+with+spaces&lang=en&page=1
// Encode special characters
echo rawurlencode('price=€100'); // price%3D%E2%82%AC100
echo rawurlencode('/path/to'); // %2Fpath%2Fto
// Decode
echo urldecode('hello+world'); // hello world
echo rawurldecode('hello%20world'); // hello world
urlencode() vs rawurlencode()
| Input | urlencode() | rawurlencode() |
|---|---|---|
hello world | hello+world | hello%20world |
a=1&b=2 | a%3D1%26b%3D2 | a%3D1%26b%3D2 |
tilde~test | tilde%7Etest | tilde~test |
http_build_query() — The Best Practice
<?php
// Recommended way to build URL query strings
$params = [
'search' => 'php url encode example',
'filters' => ['type' => 'article', 'year' => 2024],
];
echo http_build_query($params);
// search=php+url+encode+example&filters%5Btype%5D=article&filters%5Byear%5D=2024
// With custom separator
echo http_build_query($params, '', '&');
// For use inside HTML attributes
When to Use Each
- rawurlencode() — RFC 3986 compliant. Use for URL path segments and REST API parameters.
- urlencode() — Use for application/x-www-form-urlencoded data (HTML form submissions).
- http_build_query() — Use when building complete query strings from arrays. Handles nested arrays automatically.