Backend Development 4 min read

Using PHP's urlencode Function for URL Encoding

This article explains how PHP's urlencode function converts special and non‑ASCII characters into URL‑safe representations, provides example code for both English and Chinese strings, and discusses practical usage considerations such as space handling and the alternative rawurlencode function.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's urlencode Function for URL Encoding

URL encoding is essential for transmitting data on the Internet, especially when URLs contain special characters (e.g., spaces, ampersands) or non‑ASCII characters such as Chinese or Japanese text. Proper encoding ensures correct transmission and parsing.

In PHP, the built‑in urlencode function converts these characters into a URL‑safe format. The following example demonstrates encoding a simple English string.

<?php
// String to be encoded
$str = "Hello World!";

// Encode the string using urlencode
$encodedStr = urlencode($str);

// Output the encoded string
echo $encodedStr;
?>

Running this code outputs the URL‑encoded version of "Hello World!": %48%65%6c%6c%6f%20%57%6f%72%6c%64%21 .

The same function works with non‑ASCII characters. The example below encodes a Chinese phrase.

<?php
// String to be encoded
$str = "你好,世界!";

// Encode the string using urlencode
$encodedStr = urlencode($str);

// Output the encoded string
echo $encodedStr;
?>

Executing this script produces the URL‑encoded string for "你好,世界!": %e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81 .

In real applications, URL encoding is commonly used to safely pass parameters to a server, such as in GET requests, preventing special or non‑ASCII characters from breaking the URL structure.

Note that urlencode encodes spaces as "+" by default; if you need spaces encoded as "%20", use the rawurlencode function instead.

In summary, PHP's urlencode function provides a straightforward way to encode special and non‑ASCII characters in URLs, helping ensure data integrity and proper parsing in web applications.

Backendweb developmentphpurlencodeurlencoding
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login 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.