How to Use the PHP rawurlencode() Function
In this article, you will learn how to use the PHP rawurlencode() function.
PHP rawurlencode() Function
The rawurlencode() function in PHP is used to encode a URL string so that it can be safely passed as part of a query string in a URL.
The function takes a string as an argument and returns the encoded string.
rawurlencode(string $str) : string
<?php $url = "https://www.example.com/search?q=hello world"; $encoded_url = rawurlencode($url); echo $encoded_url; // Output: https%3A%2F%2Fwww.example.com%2Fsearch%3Fq%3Dhello%20world ?>
The rawurlencode() is used to encode only specific parts of a URL, such as the query string parameters. It converts all characters except letters, digits, and the characters ‘-‘ (hyphen), ‘_’ (underscore), ‘.’ (dot), and ‘~’ (tilde) into their corresponding hexadecimal representation.
For example, if you have a URL like https://www.example.com/search?q=hello world, the rawurlencode() function will encode the space character in the query string parameter q as %20. This ensures that the query string is properly formatted and can be safely passed in a URL.
It is important to encode URL parameters to ensure that the URL is properly formatted and can be safely transmitted over the internet. Without encoding, special characters such as spaces, ampersands, and semicolons could cause problems when passing the URL as part of a query string.
Note: If you want to encode the entire URL, including the domain and query string parameters, you should use urlencode() instead of rawurlencode().