INTRODUCTION
DECODING THE URL MYSTERY
Welcome to a beginner’s tutorial on Url Encode and decode in PHP. This is a topic that somehow not many people like to talk in-depth; Some of the online tutorials that I have found even goes skin deep in explaining the parameters of the encode-decode functions, and only gave a few dubious examples.
But just what is the for the URL encode-decode functions used for? Why are they necessary for building the query strings? Why is there a URL encode, and a RAW encode? That is what we will walk through in this guide – Read on to find out!
I have included a zip file with all the example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
CONFESSION
AN HONEST DISCLOSURE
Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!
NAVIGATION
TABLE OF CONTENTS
Section A | Section B | Extra |
Extra | Closing |
SECTION A
URL ENCODE DECODE
Let us now get started with the basics of URL encode and decode – What it is used for, and how to use it.
QUICK RECAP – HTML FORM SUBMIT
For a start, let us have a quick recap for the beginners on HTML forms. But what does this have anything to do with URL encoding? We will get there, so bear with this for a minute.
FORM GET EXAMPLE
When we submit the above form, it will redirect to the specified server script with a query string containing the form data. For example, http://localhost/1b-server.php?user-name=John+Doe&user-email=john%40doe.com
.
WHAT IS URL ENCODING?
Notice that the empty space in John Doe
is replaced with John+Doe
? Also, the @
in the email is replaced with john%40doe.com
? Yes, that is exactly what URL encoding is all about. There are certain rules to how the URL and query string can be formed, and in a nutshell:
- All non-alpha numeric characters will be replaced with a percent sign (%), followed by the corresponding hex code.
- White spaces will be replaced with the plus (+) sign.
- Dash, underscore, period (-_.) are the only exceptions and left as they are.
If you want to read more about query strings, I will leave a link to Wikipedia in the extras section below.
URL ENCODING IN PHP
In an HTML form, we simply have to set method="get"
and it will automatically URL encode the form data into a query string on submit. In PHP, we can use the urlencode(STRING)
function to do the same.
"John Doe",
"email" => "[email protected]"
];
// We can create a query string with urlencode
$query = "?";
foreach ($data as $key=>$value) {
$query .= urlencode($key) . "=" . urlencode($value) . "&";
}
$query = substr($query, 0,-1); // strip the last &
echo $query;
?>
This is very useful, for example, we may want to do server-to-server communication:
"John Doe",
"email" => "[email protected]"
];
// Build query string
$query = "?";
foreach ($data as $key=>$value) {
$query .= urlencode($key) . "=" . urlencode($value) . "&";
}
$query = substr($query, 0,-1);
// Let's say that we have to send some data to this URL
// $targetURL = "http://another-site.com/form.php";
$targetURL = "http://localhost/1b-server.php";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $targetURL . $query, // ! QUERY STRING APPENDED TO URL
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
]);
$result = curl_exec($curl);
if ($result === false) {
echo curl_error($curl);
echo curl_errno($curl);
} else {
print_r($result);
}
curl_close($curl);
?>
URL DECODE
Usually in a PHP script, the query string is parsed nicely into the $_GET
global variable automatically. Following up with the above example after submitting the HTML form:
$value) {
echo "KEY - $key | VALUE - $value" . PHP_EOL;
}
?>
But let’s say that we have a URL with a query string. In order to retrieve the data, we can either use the parse_url
, or urldecode
function.
";
echo "VALUE - " . urldecode($chunkB[1]) . "
";
}
?>
SECTION B
RAW ENCODE
The above section should pretty much explain URL encode and decode, but if you poke around a little longer – You will realize that there is an “alternative” raw URL encode version.
WHY RAW? WHAT’S THE DIFFERENCE?
So why are there two? Long story short – Welcome to the confusing cyber world. There is some conflicting history, but here’s the difference in a nutshell:
urldecode
works the same way as how HTML form is encoded, the same asapplication/x-www-form-urlencoded
media type.rawurldecode
works the same way as according to RFC 3986.
They are somewhat similar, but with some differences in rawurldecode
:
- Similarly, all non-alpha numeric characters will be replaced with a percent sign (%), followed by the corresponding hex code.
- White spaces will be replaced with
%20
instead of the plus sign (+). - Dash, underscore, period, and tilde (-_.~) are the exceptions (extra tilde).
A simple practice example will show you the differences:
";
// In raw encode
// dash-underscore_period.tilde~empty%20space
echo "Raw encode: " . rawurlencode($query) . "
";
?>
WHEN TO USE EACH ONE
Long story short again:
- Use
rawurlencode
on the path segment. - But use
urlencode
on the query segment.
"John Doe",
"email" => "[email protected]"
];
$query = "?";
foreach ($data as $key=>$value) {
$query .= urlencode($key) . "=" . urlencode($value) . "&";
}
$query = substr($query, 0, -1);
// The complete "safe" link ?>
">Click Here
Doh. It’s painful, but that’s how the Internet works…
EXTRA
USEFUL BITS
That’s all for this project, and here is a small section on some extras that may be useful to you.
REFERENCES
- PHP URL Encode
- PHP URL Decode
- Raw URL Encode
- Raw URL Decode
- Query Strings – Wikipedia
EXTRA
DOWNLOAD
Finally, here is the download link to all the example source code as promised.
SOURCE CODE DOWNLOAD
Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
CLOSING
WHAT’S NEXT?
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
The post PHP URL Encode & Decode – Beginner’s Guide appeared first on Code Boxx.