Backend Development 4 min read

Using PHP's urlencode Function for URL Encoding

This article explains how to use PHP's built-in urlencode function to safely encode URLs containing special or non‑ASCII characters, demonstrates encoding of both English and Chinese strings with code examples, discusses practical usage in GET requests, and notes the difference between urlencode and rawurlencode for space handling.

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

URL encoding is essential for transmitting data on the Internet when URLs contain special characters (such as spaces or ampersands) or non‑ASCII characters (such as Chinese or Japanese). PHP provides the built‑in urlencode function to convert these characters into a URL‑safe format.

The urlencode function transforms special and non‑ASCII characters into a form that can be parsed and transmitted. Below is a basic example that encodes an English string:

<?php
// 要编码的字符串
$str = "Hello World!";
// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);
// 输出编码后的字符串
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 .

When the URL contains non‑ASCII characters, such as Chinese, the same function can be used. The following example encodes a Chinese string:

<?php
// 要编码的字符串
$str = "你好,世界!";
// 使用 "urlencode" 函数对字符串进行URL编码
$encodedStr = urlencode($str);
// 输出编码后的字符串
echo $encodedStr;
?>

Executing this code produces the encoded string: %e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81 .

In real‑world scenarios, URL encoding is commonly used to pass parameters to a server, ensuring data integrity and correct parsing. For example, when sending data via a GET request, parameters should be encoded with urlencode to prevent special or non‑ASCII characters from breaking the URL structure.

Note that urlencode encodes spaces as the plus sign (+). If you need spaces encoded as %20 , use the built‑in rawurlencode function instead.

In summary, by using PHP's urlencode function, developers can easily encode special and non‑ASCII characters in URLs, ensuring reliable transmission and parsing, and should incorporate URL encoding to improve the stability and security of their PHP applications.

backend developmentsecurityweb developmentPHPURL encoding
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.