PHP urlencode Function | URL-Encode a String

PHP urlencode is an inbuilt function in PHP. It encodes a string so as to make it convenient to pass them as query parameters in the URL. The string consists of all non-alphanumeric characters except -, _ and . by replacing them with % sign followed by two hex digits. Also, it converts spaces to (+) sign. In this article, we will discuss the PHP urlencode Function. Also, we will discuss a few examples of using it.

Also, you can decode the URL encoded by this function using the PHP urldecode Function.

Syntax

string urlencode( $string )

Parameters

The PHP urlencode Function expects only one parameter. The string which you want to encode is the input to the function.

Return Value

The urlencode Function in PHP returns a string after encoding the input string so as to make it convenient to pass as a query parameter in the URL.

Input: https://concatly.com/
Output: https%3A%2F%2Fconcatly.com%2F

Input: a=1&b=2 1
Output: a%3D1%26b%3D2+1
PHP urlencode Function

Examples

Let’s discuss a few examples of using the function.

Example 1: Encode a Simple URL

For instance, you can encode a simple URL using the function like this:

<?php

	$url = "https://concatly.com/";
	echo urlencode($url);

?>

In the above example, the function replaces dot (.) with % and 2 hex characters.

OUTPUT:
https%3A%2F%2Fconcatly.com%2F

Example 2: Converting Query Parameters

Similarly, you can convert a string containing query parameters using the function in the same way.

<?php

	$url = "a=1&b=2 1";
	echo urlencode($url);

?>

In the above example, the function simply encodes url parameters. Also, notice that it converts the extra space to +.

OUTPUT:
a%3D1%26b%3D2+1

Conclusion

In this article, we discussed the PHP urlencode Function. You can read more about it on the Official PHP Documentation. Additionally, you can read about PHP String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *