PHP - URL rawurlencode() Function



The PHP URL rawurlencode() function is used to encode a string according to RFC 3986. It means that it replaces special characters in a URL. This helps to make URLs safe to transmit over the internet.

Syntax

Below is the syntax of the PHP URL rawurlencode() function −

string rawurlencode(string $str)

Parameters

This function accepts $str parameter which is the input string that needs to be encoded.

Return Value

The rawurlencode() function returns the encoded string in which all special characters are replaced with their percent-encoded values.

PHP Version

First introduced in core PHP 4, the rawurlencode() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

Here the basic example of the PHP URL rawurlencode() function to encode a simple string with spaces and special characters.

The exclamation mark and space are replaced in this example with its corresponding encoded characters.

<?php
   // Mention the string here
   $str = "Hello World!";
   $encodedString = rawurlencode($str);
   echo $encodedString;
?>

Output

The above code will result something like this −

Hello%20World%21

Example 2

Now we will try to use the rawurlencode() function and encode a URL path to make it safe.

<?php
   // Mention URL path here
   $urlPath = "/PHP/PhpProjects/filename.html";
   $encodedPath = rawurlencode($urlPath);
   echo $encodedPath; 
?> 

Output

After running the above program, it generates the following output −

%2FPHP%2FPhpProjects%2Ffilename.html

Example 3

Now the below code encodes a query string with different special characters using rawurlencode() function.

<?php
   // Mention string here
   $str = "name=Amit Sharma&age=33";
   $encodedQuery = rawurlencode($str);
   echo $encodedQuery; 
?> 

Output

This will create the below output −

name%3DAmit%20Sharma%26age%3D33

Example 4

In the following example, we are using the rawurlencode() function to encode an entire URL.

<?php
   // Mention URL path here
   $url = "https://www.tutorialspoint.com/search?q=hello world&lang=en";
   $encodedURL = rawurlencode($url);
   echo $encodedURL; 
?> 

Output

When the above program is executed, it will produce the below output −

https%3A%2F%2Fp.rizon.top%3A443%2Fhttps%2Fwww.tutorialspoint.com%2Fsearch%3Fq%3Dhello%20world%26lang%3Den%

Example 5

This example shows how you can create a URL with a dynamic path that have special characters so using rawurlencode() function the special characters will be encoded.

<?php
   // Mention URL path here
   echo '<a href="http://tutorialspoint.com/department_list_script/',
    rawurlencode('quality tutorials and courses'), '">';
?>

Output

After executing the program, we will get the below output −

<a href="http://tutorialspoint.com/department_list_script/quality%20tutorials%20and%20courses">   
php_function_reference.htm
Advertisements