This page explains the ideas. The URL Functions index lists all 10 function guides.
Encode each part.
Encode every value on its own with urlencode() or rawurlencode(). If you encode a whole URL, the : and / characters break.
Syntax
PHP Syntax
The most common URL tasks in one place:
PHP
<?php
// Encode a value for a query string
$q = urlencode("php & mysql"); // php+%26+mysql
// Build a whole query string from an array
$query = http_build_query(["q" => "php", "page" => 2]); // q=php&page=2
// Split a URL into parts
$parts = parse_url("https://example.com/a?x=1");
// Turn data into base64 text and back
$b64 = base64_encode("Hello"); // SGVsbG8=
$text = base64_decode($b64); // Hello
Reference
Core Ideas
What to remember when you work with URLs in PHP:
Idea
Example
Remember
Query value
urlencode($text)
A space becomes +. Use it for form-style data.
Path piece
rawurlencode($text)
A space becomes %20. Use it for URL paths.
Whole query
http_build_query($array)
Builds a=1&b=2 and encodes every value.
Split a URL
parse_url($url)
Returns scheme, host, path, query and more.
Base64
base64_encode($data)
Turns data into plain text. It is not encryption.
Page info
get_headers($url)
Needs network access. Reads the response headers.
Code
PHP Examples
Three short scripts that show how the URL functions are used.
They are the functions that build, read and encode web addresses. The main ones are urlencode(), rawurlencode(), http_build_query(), parse_url(), base64_encode() and base64_decode().
urlencode() writes a space as + and is meant for form-style query values. rawurlencode() writes a space as %20 and is meant for URL paths.
Use http_build_query($array). It encodes each value and joins the pairs with &.
Use parse_url($url) for an array of parts, or pass a PHP_URL_* constant to get one part.
No. Base64 is only an encoding. Anyone can decode it, so do not use it to hide secrets.
Practice the examples here, then open the URL Functions index for all 10 function guides.