PHP urlencode Function: Usage, Parameters, and Examples
This article explains the PHP urlencode() function, describing how it converts characters to URL‑encoded format, detailing its parameter and return value, and providing two practical code examples that demonstrate encoding strings for safe inclusion in URLs.
The urlencode() function converts predefined characters in a string to HTML entities suitable for URL query strings, encoding spaces as plus signs and non‑alphanumeric characters as percent‑encoded values.
Parameter: $str – the string to be encoded.
Return value: A string where all characters except -_. are replaced with % followed by two hexadecimal digits; spaces become + .
Example 1: Encoding a simple string containing both English and Chinese characters.
<?php
$userinput = "hello 你好";
echo '<a href="mycgi?foo=' . urlencode($userinput) . '">';
?>Output:
href="mycgi?foo=hello+%E4%BD%A0%E5%A5%BD">Example 2: Encoding multiple query parameters and safely outputting them with htmlentities() .
<?php
$foo = "hello";
$bar = "weorld";
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>Output:
<a href="mycgi?foo=hello&bar=weorld">Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.