PHP urlencode() Function
Quick summary: The PHP urlencode() function encodes a string for use in a URL query.
PHP urlencode() Syntax
urlencode(string $string): string
PHP
PHP urlencode() Basic examples
var_dump(urlencode('hello world'));
PHP
Output:
string(11) "hello+world"
Encodes spaces as plus signs.
PHP urlencode() Real-world usage
$query = 'page=1&sort=asc';
echo urlencode($query);
PHP
Output:
page%3D1%26sort%3Dasc
Encodes query strings safely.
PHP urlencode() Edge cases
var_dump(urlencode('a+b'));
PHP
Output:
string(5) "a%2Bb"
Plus signs are encoded.
PHP urlencode() Common mistakes
Using urlencode for URL paths
urlencode is meant for query strings.
Incorrect
urlencode('/path/file');
Correct
rawurlencode('/path/file');
Use rawurlencode for paths.
PHP urlencode() Frequently Asked Questions
What does urlencode() do in PHP?
Encodes a string for safe use in URLs.
Difference from rawurlencode()?
urlencode replaces spaces with +, rawurlencode uses %20.
Use case?
Encoding query parameters.
Does it modify string?
Returns encoded string.
Is it reversible?
Yes via urldecode().
Handles UTF-8?
Yes.
Common mistake?
Using wrong encoding function.
Performance?
Fast.
Can encode full URLs?
Not recommended.
When to use rawurlencode()?
For path segments.
Used in forms?
Yes.
Alternative?
rawurlencode().