Backend Development 4 min read

Using PHP's urlencode Function to Encode URLs

This article explains the importance of URL encoding for transmitting data safely on the internet, demonstrates how to use PHP's built‑in urlencode function with examples for both ASCII and non‑ASCII strings, and highlights considerations such as space handling and the alternative rawurlencode function.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's urlencode Function to Encode URLs

URL encoding is an essential technique for transmitting data on the Internet; when a URL contains special characters such as spaces or ampersands, or non‑ASCII characters like Chinese or Japanese, it must be encoded to ensure correct transmission and parsing.

The PHP built‑in function urlencode converts special and non‑ASCII characters in a string into a URL‑safe format that can be parsed and transmitted.

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

Executing the above code outputs the URL‑encoded version of the string “Hello World!” as %48%65%6c%6c%6f%20%57%6f%72%6c%64%21 .

When a URL contains non‑ASCII characters, the same urlencode function can be used; the following example demonstrates encoding a Chinese string.

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

Running this code outputs the URL‑encoded representation of “你好,世界!” as %e4%bd%a0%e5%a5%bd%ef%bc%8c%e4%b8%96%e7%95%8c%ef%bc%81 .

In practical applications, URL encoding is commonly used to pass parameters to a server, for example in GET requests, to preserve data integrity and prevent special or non‑ASCII characters from breaking the URL structure.

Note that urlencode encodes spaces as a plus sign (+); if you need spaces encoded as %20 , use the rawurlencode function instead.

In summary, using PHP’s urlencode function allows developers to easily encode special and non‑ASCII characters in URLs, ensuring correct transmission, parsing, and improving the stability and security of PHP applications.

PHP8 video tutorial

Scan the QR code to receive free learning materials

Backend DevelopmentPHPData TransmissionURL encodingweb programming
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.