In PHP, encoding a URL entails using urlencode()
to convert a URL string into formats that are understandable by the system.
urlencode()
function do?This function does the following:
urlencode()
function, the encoded URL can enjoy over-the-internet transmission using the ASCII character set. This will enable our request to be successfully sent.That notwithstanding, URLs can and do contain characters which are not part of the ASCII set. This means that such characters will be forced to a valid ASCII set.
Generally speaking, what happens here is that the URL encoding process will replace unsafe ASCII characters with a “%” followed by two hexadecimal digits, so as to safely transmit the URL. It is also important to know that a URL cannot contain spaces. If by any chance there is space in the URL, the urlencode()
function will replace this space with a plus (+
) or a %20
. To understand this, let’s see some examples:
string urlencode( $input )
urlencode()
function needs only a single compulsory argument which is the URL string to be encoded.Now, let’s use the code examples below to understand better.
<?php// let return the encoded educative.io site$siteAddress = 'https://www.educative.io';$encoded = urlencode($siteAddress);echo $encoded;?>
In the code above, we encoded the simple address https://www.educative.io
with the :
and //
special characters replaced, as indicated in the result with %3A
and %2F%2F
respectively. This kind of replacement is what happens with other special characters not recognized as part of the ASCII set.
Let’s see another example with a range of addresses, where more twists will be added.
<?php// let save different urls in some variables// this will contain space$siteAddress1 = 'https://go ogle.com';//alot of special characters.//This address is common in php codes underdevelopment$siteAddress2 = 'localhost/post/user.php?id=$_POST["id"]';// Just painting possible scenarios$siteAddress3 = 'https://forum.com/joinforsure?orStop!(now)';$encoded1 = urlencode($siteAddress1);$encoded2 = urlencode($siteAddress2);$encoded3 = urlencode($siteAddress3);echo $encoded1;echo $encoded2;echo $encoded3;?>
These URLs are ASCII encoded because
With ASCII, developers can design interfaces that both humans and computers understand. ASCII converts a string data into a character set which can be interpreted and displayed as plain text that can be read by people, and data that can be used by computers.