PHP Encoding Guide

How To Encode PHP Code

By Letters2NumbersConverter.com  ·  May 14, 2026

How To Encode PHP Code covers the built-in functions PHP provides for every major encoding format — from URL-safe strings to Base64 binary data, HTML entity escaping, JSON serialisation, and one-way password hashing. PHP ships with all of these in its standard library, so you rarely need a third-party package. The sections below walk through each category with real function signatures, concrete examples, and notes on when to reach for one function over another.

URL Encoding in PHP

PHP provides two single-value encoding functions and one array-level helper for building query strings. The difference between the first two trips up developers more often than it should.

urlencode() and urldecode()

urlencode($str) is designed for query string values. It encodes spaces as + and percent-encodes every character that is not an unreserved alphanumeric, a hyphen, an underscore, or a period. Its inverse is urldecode($str).

<?php
$query = urlencode('hello world & goodbye');
// hello+world+%26+goodbye

echo urldecode($query);
// hello world & goodbye

rawurlencode() and rawurldecode()

rawurlencode($str) follows RFC 3986 and encodes spaces as %20 rather than +. Use this for URL path segments, where a literal + is not treated as a space. Its inverse is rawurldecode($str).

<?php
$slug = rawurlencode('San Francisco/CA');
// San%20Francisco%2FCA

// Use rawurlencode for path segments:
$url = 'https://example.com/cities/' . rawurlencode('New York');
// https://example.com/cities/New%20York

http_build_query()

When you need to assemble an entire query string from an array, http_build_query(array $data) is the right tool. It handles the encoding automatically, joins pairs with &, and deals correctly with nested arrays and numeric keys.

<?php
$params = ['name' => 'John Doe', 'city' => 'New York'];
echo http_build_query($params);
// name=John+Doe&city=New+York

// Append it to a URL:
$url = 'https://api.example.com/search?' . http_build_query($params);

If you need %20 instead of + for spaces, pass PHP_QUERY_RFC3986 as the fourth argument: http_build_query($params, '', '&', PHP_QUERY_RFC3986).

For hands-on experimentation with URL encoding output, try the URL encoding guide or use the interactive HTML Encoder / Decoder tool.

HTML Encoding in PHP

Outputting untrusted user data directly into HTML is the root cause of the majority of XSS vulnerabilities. PHP's HTML encoding functions neutralise the characters that HTML parsers treat as special before the string ever reaches the browser.

htmlspecialchars() — the right choice for XSS prevention

htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8') converts the five characters with HTML special meaning into their safe entity equivalents:

CharacterEntity
&&amp;
<&lt;
>&gt;
"&quot;
'&#039;

Always pass ENT_QUOTES | ENT_HTML5 and an explicit charset of 'UTF-8' — the defaults have changed between PHP versions and omitting them silently misses single-quote encoding in older configurations.

<?php
$userInput = '<script>alert("xss")</script>';
$safe = htmlspecialchars($userInput, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;

echo '<p>' . $safe . '</p>';
// Renders as literal text — no script executes.

The inverse function is htmlspecialchars_decode($str, ENT_QUOTES | ENT_HTML5).

htmlentities() — more aggressive, usually unnecessary

htmlentities($str, ENT_QUOTES | ENT_HTML5, 'UTF-8') goes further: it converts every character that has an HTML entity equivalent — accented letters, currency symbols, and so on. For most UTF-8 applications this is overkill. htmlspecialchars() is sufficient and produces smaller, more readable output. The inverse is html_entity_decode().

strip_tags() — when you want removal, not escaping

strip_tags($str) removes HTML and PHP tags entirely from a string. This is different from encoding — it does not escape the tags, it deletes them. Use it when you want plain text output and have no need for the original markup. It does not protect against XSS on its own if the output is later placed inside a JavaScript context or an HTML attribute.

For more on HTML encoding, see the HTML encoding guide and the HTML Encoder / Decoder tool.

Base64 Encoding in PHP

Base64 encodes arbitrary binary data as a string of printable ASCII characters. PHP's built-in functions make it straightforward.

base64_encode() and base64_decode()

<?php
// Encode a plain string
$encoded = base64_encode('Hello World');
// SGVsbG8gV29ybGQ=

// Decode it back
$decoded = base64_decode($encoded);
// Hello World

// Encode a binary file for embedding in JSON or a data URI
$imageData = file_get_contents('image.png');
$base64Image = base64_encode($imageData);
$dataUri = 'data:image/png;base64,' . $base64Image;

base64_decode() returns false on invalid input, so always check the return value before using the result. Pass true as the second argument ($strict) if you want it to return false for strings containing characters outside the Base64 alphabet, rather than silently ignoring them.

Common Base64 use cases in PHP

  • Embedding binary data (images, PDFs) inline in a JSON API response
  • Storing binary blobs in a database text column
  • MIME email attachments (encoded by the mail library, but the underlying call is Base64)
  • Encoding the header and payload segments of a JWT (using the URL-safe Base64URL variant)

Try encoding and decoding Base64 strings with the Base64 Encoder / Decoder tool.

JSON Encoding in PHP

JSON is the standard interchange format for REST APIs, and PHP's json_encode() / json_decode() pair handles serialisation and deserialisation without any external dependencies.

json_encode()

<?php
$data = [
    'name'    => 'Héloïse',
    'website' => 'https://example.com/path/to/page',
    'score'   => 42,
];

// Default — escapes non-ASCII and slashes
echo json_encode($data);
// {"name":"H\u00e9lo\u00efse","website":"https:\/\/example.com\/path\/to\/page","score":42}

// More readable — keep UTF-8 and unescaped slashes
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// {"name":"Héloïse","website":"https://example.com/path/to/page","score":42}

// Pretty-print for debugging
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Key flags to know:

  • JSON_PRETTY_PRINT — adds newlines and indentation, useful for debugging and log files
  • JSON_UNESCAPED_UNICODE — keeps UTF-8 characters as-is instead of converting them to \uXXXX escape sequences
  • JSON_UNESCAPED_SLASHES — prevents forward slashes from being escaped as \/, keeping URLs readable

json_decode()

<?php
$json = '{"name":"Alice","roles":["admin","editor"]}';

// Decode to associative array (pass true as second arg)
$data = json_decode($json, true);
echo $data['name'];       // Alice
echo $data['roles'][0];   // admin

// Decode to object (default)
$obj = json_decode($json);
echo $obj->name;          // Alice

Error checking

json_encode() returns false on failure (for example, when the input contains non-UTF-8 sequences). json_decode() returns null on parse failure. Always check for errors using json_last_error() (returns an integer constant) or the more descriptive json_last_error_msg().

<?php
$result = json_decode('{ invalid json }', true);
if (json_last_error() !== JSON_ERROR_NONE) {
    error_log('JSON decode failed: ' . json_last_error_msg());
}

Hash Encoding in PHP — One-Way Only

Hashing is not encoding

Encoding (Base64, URL, JSON) is a reversible transformation. Hashing is one-way: you cannot recover the original value from a hash. Do not confuse the two, and never use base64_encode()to "protect" passwords.

hash() — general-purpose hashing

<?php
// SHA-256 hex digest of a string
$hash = hash('sha256', 'Hello World');
// a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

// List all available algorithms
$algorithms = hash_algos();

password_hash() and password_verify() — for passwords

For password storage, never use md5() or sha1(). These produce fast hashes that are trivially crackable with pre-computed rainbow tables or GPU-accelerated brute force. PHP's password_hash() uses bcrypt (or Argon2 with PASSWORD_ARGON2ID), automatically generating and embedding a random salt, and applying a work factor that makes brute-force attacks computationally expensive.

<?php
// Hash a password before storing it
$hash = password_hash($plainPassword, PASSWORD_BCRYPT);
// $2y$10$... — a 60-character bcrypt string including the salt

// Verify a login attempt against the stored hash
if (password_verify($plainPassword, $hash)) {
    // Password is correct — log the user in
} else {
    // Invalid password
}

// Check if the hash needs rehashing (e.g. after a cost factor change)
if (password_needs_rehash($hash, PASSWORD_BCRYPT)) {
    $hash = password_hash($plainPassword, PASSWORD_BCRYPT);
    // Update the stored hash in the database
}

Choosing the Right PHP Encoding Function

Use this table as a quick reference. The right choice depends entirely on where the output will be used.

Use caseFunction to use
Single query parameter valueurlencode() or rawurlencode()
Full query string from an arrayhttp_build_query()
URL path segment (RFC 3986)rawurlencode()
HTML output — prevent XSShtmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8')
Remove HTML tags entirelystrip_tags()
Binary data in a text field or JSONbase64_encode()
Data to/from a JSON APIjson_encode() / json_decode()
General-purpose cryptographic hashhash('sha256', $str)
Password storagepassword_hash() / password_verify()

Frequently Asked Questions

What is the difference between urlencode() and rawurlencode() in PHP?

urlencode() encodes spaces as +, which is correct for the application/x-www-form-urlencoded format used in query strings. rawurlencode() encodes spaces as %20, which is correct for URL path segments under RFC 3986. In a path, a literal + means a plus sign — not a space.

Which PHP function should I use to prevent XSS in HTML output?

Use htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8'). It converts the five characters that have special meaning in HTML (&, <, >, ", ') to safe HTML entities. htmlentities() also works but encodes far more characters than necessary.

How do I encode a file as Base64 in PHP?

Read the file with file_get_contents() and pass the result to base64_encode(): $encoded = base64_encode(file_get_contents('image.png'));. This produces a Base64 string you can embed in a data URI, a JSON payload, or a database text column.

Is hashing the same as encoding in PHP?

No. Encoding is always reversible — you can always decode back to the original. Hashing is a one-way transformation: you cannot recover the original input from a hash. Use password_hash() for passwords and hash('sha256', $str) for general integrity checks. Never use md5() or sha1() for password storage.

How do I build a URL query string from a PHP array?

Use http_build_query(array $data). It handles all encoding, joining, and nested-array expansion automatically. For example, http_build_query(['name' => 'John Doe', 'city' => 'New York']) returns name=John+Doe&city=New+York.

Related Tools and Guides