Skip to content
PHP Logo

What are the advantages and disadvantages of using rawurlencode() versus urlencode() for encoding URLs in PHP?

When encoding URLs in PHP, rawurlencode() should be used when encoding entire URLs, as it encodes characters that urlencode() does not, such as spaces and special characters. However, rawurlencode() may encode characters that should not be encoded in certain contexts, such as the forward slash (/) in URLs. In these cases, urlencode() can be used for encoding query string parameters.

php
// Using rawurlencode() for encoding entire URLs
$url = 'https://www.example.com/page with spaces.php';
$encoded_url = rawurlencode($url);
echo $encoded_url;

// Using urlencode() for encoding query string parameters
$query_param = 'search query';
$encoded_param = urlencode($query_param);
echo $encoded_param;