out()

function out(?string $input, string $output_format = 'html', string $encoding = 'UTF-8'): string

Description

Provides a single, explicit, and security-focused way to safely output strings across multiple contexts. This function eliminates ambiguity, reduces developer error, and prevents cross-site scripting (XSS) vulnerabilities caused by incorrect escaping. Rather than remembering which escaping function to use in each scenario, you call out() and explicitly declare how the output will be used.

Parameters

ParameterTypeDescription
$input string|null The raw, untrusted input value to be safely escaped for output. If null is provided, it is internally converted to an empty string.
$output_format string (optional) The desired output format. Possible values are 'html' (default), 'attribute', 'xml', 'json', or 'javascript'. This defines the output context and determines which escaping strategy is used. Defaults to 'html'.
$encoding string (optional) The character encoding to use for escaping. Defaults to 'UTF-8'. Unless working with a legacy system that requires a different encoding, this parameter should not be changed.

Return Value

TypeDescription
stringThe escaped and formatted string, ready for safe inclusion in the specified context.

Output Formats

FormatContextUse Case
html HTML content between tags Default. For displaying user content in paragraphs, divs, spans, etc.
attribute HTML attribute values For inserting data into HTML attributes like title, alt, data-*
xml XML character data For XML content (not tags). Uses XML 1.0 escaping rules.
json JSON output For API responses, AJAX data, or embedding JSON in <script> tags
javascript JavaScript string content For embedding string values inside JavaScript string literals

Example #1: Basic HTML Output

This example demonstrates how the out() function escapes user-generated content to prevent XSS attacks when displaying it in HTML:

Result in the browser (what the user sees):

The dangerous tags are displayed as plain text rather than being interpreted as HTML or JavaScript. Importantly, no alert box appears - the JavaScript is not executed.

The key point to notice, here, is that the JavaScript code does not get executed.

Generated HTML source (viewable via "View Page Source"):

The out() function converts characters like <, >, and & into their corresponding HTML entities, ensuring the content is rendered safely as text.


Example #2: HTML Attribute Output

This example demonstrates how the out() function safely escapes user data when inserting it into HTML attributes, preventing attribute injection attacks:

Result in the browser (what the user sees):

The browser displays the visible content of the div element:

Developers often use the 'title' attribute for generating tooltips.

A tooltip is a small pop-up message that appears when a user hovers over (or focuses on/taps) a UI element, providing brief contextual information or help.

If the 'title' attribute was being used for generating tooltips, hovering over the element would display:

Generated HTML source (viewable via "View Page Source"):

The out() function with the 'attribute' parameter converts special characters like & and " into their HTML entity equivalents (&amp; and &quot;), preventing attackers from breaking out of the attribute context or injecting malicious attributes.


Example #3: XML Output

This example demonstrates how the out() function safely escapes content when generating XML documents, ensuring well-formed and valid XML output:

What is XML?

XML (eXtensible Markup Language) is a markup language used for storing and transporting structured data. Unlike HTML, which is designed for displaying content in web browsers, XML is designed for data exchange between systems.

Common use cases include:

  • API responses (RESTful web services, SOAP)
  • Configuration files
  • Data feeds (RSS, Atom)
  • Document formats (SVG, DOCX internals)
  • Sitemaps for search engines

Result in the browser (what the user sees):

When viewed in a browser that renders XML, the content displays as:

Generated XML source (viewable via "View Page Source"):

The out() function with the 'xml' parameter converts special characters that have meaning in XML into their corresponding entity references. In this example, & becomes &amp; and the apostrophe becomes &apos;. This ensures the XML remains well-formed and parseable by XML processors, preventing syntax errors or data corruption when the XML is consumed by other systems.


Example #4: JSON API Response

This example demonstrates how the out() function safely encodes content when generating JSON responses, preventing XSS attacks in JavaScript contexts and ensuring valid JSON syntax:

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data format used for exchanging information between a server and a client. It's the standard format for modern web APIs.

Common use cases include:

  • RESTful API responses
  • AJAX requests and responses
  • Configuration files
  • Data storage (NoSQL databases like MongoDB)
  • Inter-service communication in microservices architectures

Result in the browser (what the user sees):

When this JSON response is received by a client application and parsed, the message value would be:

Importantly, the dangerous script tags are treated as plain text data, not executable code.

Generated JSON source (viewable via "View Page Source" or network inspector):

The out() function with the 'json' parameter uses JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, and JSON_HEX_QUOT flags to convert potentially dangerous characters into their Unicode escape sequences. In this example, < becomes \u003C, > becomes \u003E, and quotes are properly escaped. This prevents XSS attacks when the JSON is embedded in HTML or processed by JavaScript, while maintaining valid JSON syntax that can be safely parsed by any JSON decoder.


Example #5: Embedding JSON in HTML

This example demonstrates how the out() function safely embeds JSON data within HTML <script> tags, allowing JavaScript to consume server-side data without creating security vulnerabilities:

Why embed JSON in HTML?

A common web development pattern involves passing server-side data (from PHP) to client-side JavaScript. Rather than making separate AJAX requests, developers often embed data directly in the HTML during initial page load for better performance and immediate availability.

Common use cases include:

  • Passing user profile data to JavaScript applications
  • Initializing front-end frameworks (React, Vue, Angular) with server data
  • Providing configuration settings to client-side code
  • Hydrating single-page applications (SPAs) with initial state
  • Passing authentication tokens or session data

Result in the browser (what the user sees):

The JavaScript executes successfully and the console displays:

The userData object is properly initialized and accessible to JavaScript code throughout the page.

Generated HTML source (viewable via "View Page Source"):

The out() function with the 'json' parameter ensures that the JSON data is properly escaped for embedding within <script> tags. This prevents XSS attacks that could occur if user-controlled data contained malicious payloads like </script><script>alert('XSS')</script>. By converting characters like <, >, &, and quotes into their Unicode escape sequences, the function ensures the data remains safely contained within the JavaScript context while being fully parseable as valid JSON.


Example #6: JavaScript String Literal

This example demonstrates how the out() function safely escapes string values when embedding them directly inside JavaScript string literals, preventing syntax errors and code injection attacks:

JavaScript String Literals vs JSON Objects

While Example #5 showed how to embed complete JSON objects in JavaScript, this example focuses on embedding a simple string value directly within JavaScript code as a string literal.

The key difference is that the 'javascript' format parameter removes the surrounding quotes that JSON encoding adds, making the output suitable for insertion between quote marks in JavaScript code.

Common use cases include:

  • Dynamically setting JavaScript variable values from PHP
  • Generating inline event handlers with dynamic content
  • Creating JavaScript alert or confirmation messages with server data
  • Building JavaScript code snippets dynamically
  • Passing single string values rather than complex objects

Result in the browser (what the user sees):

An alert box appears displaying:

The JavaScript correctly interprets the string literal with the embedded quotes.

Generated HTML source (viewable via "View Page Source"):

The out() function with the 'javascript' parameter properly escapes special characters that would break JavaScript string syntax. In this example, the double quotes within the string are escaped as \", preventing them from prematurely terminating the string literal. The function also handles other dangerous characters like single quotes, backslashes, and line breaks, ensuring the resulting JavaScript code is syntactically valid and immune to injection attacks where malicious users might try to break out of the string context to execute arbitrary code.


Example #7: Using Named Parameters

This example demonstrates how to use PHP's named parameters feature (introduced in PHP 8.0) with the out() function, providing clearer and more maintainable code when specifying parameters:

What are Named Parameters?

Named parameters (also called named arguments) allow you to specify function arguments by their parameter name rather than relying solely on position. This PHP 8.0+ feature makes code more readable and allows you to skip optional parameters without needing placeholder values.

Benefits of using named parameters with out():

  • Improved readability - the parameter's purpose is immediately clear
  • Flexibility to specify only the parameters you need, in any order
  • Easier to override encoding without specifying format (skips middle parameter)
  • Self-documenting code that's easier to maintain
  • Reduces errors when changing less common parameters like encoding

Note: Named parameters require PHP 8.0 or later.

Understanding the examples:

In the first example, encoding: 'ISO-8859-1' explicitly names the third parameter, making it clear that we're overriding the default UTF-8 encoding. This is particularly useful when working with legacy systems or databases that use different character encodings.

In the second example, output_format: 'json' names the second parameter, making the intent obvious even without seeing the function signature. This approach is especially valuable in larger codebases where developers may not be familiar with every function's parameter order.

Important: Named parameters require PHP 8.0 or higher. If your project needs to support older PHP versions, you must use positional parameters instead.

Using named parameters with the out() function enhances code clarity and makes your intentions explicit, particularly when overriding default values like the encoding parameter or when you want to emphasize which output format is being used. This is especially valuable in team environments where code readability and maintainability are priorities.


Output Comparison

Given the input: <script>alert('xss')</script>

FormatOutputNotes
html &lt;script&gt;alert(&#039;xss&#039;)&lt;/script&gt; Safe for HTML content between tags
attribute &lt;script&gt;alert(&#039;xss&#039;)&lt;/script&gt; Identical to 'html' but semantically distinct
xml &lt;script&gt;alert(&apos;xss&apos;)&lt;/script&gt; Uses XML-specific escaping
json "\u003Cscript\u003Ealert('xss')\u003C\/script\u003E" Valid JSON string with Unicode escapes
javascript \u003Cscript\u003Ealert('xss')\u003C\/script\u003E Same as JSON but without surrounding quotes

How Each Format Works:

  • HTML and Attribute: Use htmlspecialchars() with ENT_QUOTES flag, escaping <, >, &, ", and '
  • XML: Uses htmlspecialchars() with ENT_XML1 flag for XML 1.0-specific escaping
  • JSON: Uses json_encode() with flags including JSON_HEX_TAG, JSON_HEX_AMP, JSON_UNESCAPED_UNICODE, and JSON_THROW_ON_ERROR
  • JavaScript: Same as JSON but removes surrounding quotes for inline use in string literals

Important Note About JavaScript Format: The javascript format returns string content only. You must supply the surrounding quotes in your code:

Common Pitfalls to Avoid:

  • Double-escaping: Don't pass already-escaped data through out() again
  • Wrong format: Using 'html' format for JSON will produce invalid JSON
  • Missing quotes: The 'javascript' format requires you to add quotes around the output
  • Unquoted attributes: Always use quotes around HTML attributes, even with the 'attribute' format

Security Best Practices:

  • Always escape output from user input, databases, or external sources
  • Choose the correct format for your output context
  • Ensure document encoding matches the $encoding parameter (UTF-8 recommended)
  • Use the 'json' format for embedding complex data structures in JavaScript
  • When using 'attribute' format, always quote your HTML attributes

Exceptions

ExceptionWhen Thrown
InvalidArgumentException If an unsupported $output_format is provided
RuntimeException If character encoding fails due to invalid encoding specification
JsonException If JSON encoding fails (malformed UTF-8, circular references, etc.)

Notes

  • The function guarantees a string return value by converting null inputs to empty strings
  • Character encoding is critical for security - mismatched encoding can allow XSS attacks
  • The 'html' and 'attribute' formats produce identical output but represent different semantic contexts
  • JSON output includes proper Unicode escapes for dangerous characters, providing defense-in-depth protection
  • The function follows a "fail fast" approach, throwing exceptions rather than silently producing unsafe output
  • Requires PHP 7.3+ for JSON_THROW_ON_ERROR flag support