PHP urlencode() Function: Usage, Parameters, Return Value, and Examples
This article explains PHP's urlencode() function, detailing its syntax, parameter, return value, and providing two practical code examples while warning about HTML entity conflicts and recommending safe output methods.
The PHP urlencode() function encodes a string so it can be safely used in the query part of a URL, converting non‑alphanumeric characters (except -_. ) to percent‑encoded sequences and spaces to plus signs, matching the application/x‑www‑form‑urlencoded format.
Syntax: string urlencode(string $str) Parameter $str is the string to be encoded. The function returns the encoded string.
Example 1 demonstrates encoding user input directly within an anchor tag:
<?php
echo '<a href="mycgi?foo=' . urlencode($userinput) . '">';
?>Example 2 builds a query string from multiple variables, encodes each part, and then safely outputs the link using htmlentities() to avoid HTML entity conflicts:
<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>Be cautious of variables that may contain HTML entities such as &, ©, or £ because browsers will interpret them; using htmlentities() or htmlspecialchars() is recommended.
Reference: W3C HTML4 notes on URL encoding.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
