PHP » Strings » urlencode()

Syntax:
string urlencode(string data)
data
Data to be encoded.

Encodes data to be sent in a URL.

Data passed through a URL cannot contain spaces and other special characters. urlencode() encodes a string so that it can be passed as a variable in a URL.

Examples

Code:
<?php

$s = "This is a test string";

$url = "urlencode.php?data=" . urlencode($s);
print "<a href=\"$url\">Click me</a><br>";
if (isset($_REQUEST["data"])) {
   print "URL: " . $_SERVER['REQUEST_URI'] . "<br>";
   print "Decoded data: " . urldecode($_REQUEST["data"]);
}

?>
Output:
Click me
URL: /samples/strings/urlencode.php?data=This+is+a+test+string
Decoded data: This is a test string
Explanation:

urlencode() is used to create a URL for a link. When the user clicks the link the page is reloaded with a string sent in the URL. The data in the URL is decoded and printed.

See Also: