Developer Documentation
PHP
Updated September 19, 2026

URL Encoding and Decoding in PHP

Percent-encode URL components correctly and distinguish path, query, and form encoding in PHP.

URL encoding is context-sensitive. A path segment, a query value, and application/x-www-form-urlencoded data do not use exactly the same escaping rules, so prefer APIs designed for the specific component you are building.

Quick Start#

The following example uses the standard PHP API or a widely used package for this task.

Percent-encode a component#

PHP
1<?php2$value = "café & tea + cake";3$encoded = rawurlencode($value);4$decoded = rawurldecode($encoded);56echo $encoded . PHP_EOL;7echo $decoded . PHP_EOL;

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Build an HTTP query#

PHP
1<?php2$query = http_build_query([3    'q' => 'café & tea',4    'page' => ,5], '', '&', PHP_QUERY_RFC3986);67echo "https://example.com/search?$query";

Important Notes#

rawurlencode follows RFC 3986 percent encoding; urlencode uses form-style space-to-plus behavior. Choose intentionally.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement URL Encoding in other languages: