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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP urlencode() Function: Usage, Parameters, Return Value, and Examples

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.

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.

Backendweb-developmenturlencodeurl-encoding
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.