Master URL Encoding in PHP: How to Use urlencode and rawurlencode

This article explains why URL encoding is essential for transmitting data with special or non‑ASCII characters, demonstrates how to use PHP’s urlencode (and rawurlencode) functions with example code for both English and Chinese strings, and highlights practical considerations such as space handling.

php Courses
php Courses
php Courses
Master URL Encoding in PHP: How to Use urlencode and rawurlencode

URL encoding is essential when transmitting data on the internet. When a URL contains special characters (e.g., spaces, ampersand) or non‑ASCII characters (e.g., Chinese, Japanese), it must be encoded to ensure correct transmission and parsing. In PHP, the built‑in urlencode function is used for this purpose.

The urlencode function converts special and non‑ASCII characters into a URL‑safe format. Example for an English string:

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

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

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

Running the 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 works:

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

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

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

The result is: %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 pass parameters to a server, for example in GET requests, to preserve data integrity.

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

By using PHP’s urlencode (or rawurlencode) you can reliably encode special and non‑ASCII characters in URLs, improving the stability and security of your programs.

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.

PHPURL encodingrawurlencodeurlencode
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

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.