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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP urlencode Function: Usage, Parameters, and Examples

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">
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPurlencode
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.