How can I properly URL encode a string in PHP?

How can I properly URL encode a string in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How can I properly URL encode a string in PHP?

When building a search interface where users submit queries via search.php?query=your query, the immediate instinct is often to simply pass the input straight to the database or search logic. However, leaving raw user input exposed in the query string without encoding it invites two distinct problems: breaking the URL structure and exposing your application to cross-site scripting (XSS) vulnerabilities if that data ever renders in an HTML context later on.

The standard PHP function for preparing data meant to be included in a URL is urlencode(). This function converts non-alphanumeric characters into percent-encoded sequences, such as turning a space into %20 or a question mark into %3F. The output of urlencode() is a single string that represents the entire query value.

Consider a scenario where a user searches for "hello world". If you append this directly to your URL without encoding, the resulting string becomes search.php?query=hello world. While browsers handle spaces gracefully by converting them automatically, relying on browser behavior is fragile and can break when the data contains other special characters like & or =. If a user searches for "test & value", the raw URL becomes search.php?query=test & value. The server might interpret the & as the start of a new query parameter, potentially overwriting your intended query variable with just value and treating test as an empty or missing parameter. Using urlencode() prevents this parsing ambiguity by ensuring the entire string is treated as one atomic unit within the URL structure.

However, there is a critical distinction between encoding for URLs and encoding for HTML. If your goal is solely to sanitize data before storing it in a database or passing it to another script, urlencode() is appropriate because it adheres to RFC 3986 standards for query strings. But if you intend to display that search term back to the user in an HTML page, using urlencode() might result in double-encoding issues or visible percent signs in the output. For rendering data inside <a href> tags or JavaScript properties where the string is part of a URL but displayed as text, htmlentities() or htmlspecialchars() are often better choices depending on the specific attribute context.

A common pitfall arises when dealing with multi-byte character sets like UTF-8. While urlencode() supports UTF-8 by default in modern PHP versions, it encodes characters based on their byte representation. If your application relies on raw bytes for encoding but expects logical character handling, you might need to ensure the string is explicitly encoded as UTF-8 before calling the function, although standard usage usually handles this correctly out of the box.

When decoding data retrieved from a URL, use urldecode(). This function reverses the percent-encoding process. It is important to note that if you have previously used htmlentities() on the data before encoding it for the URL, simply using urldecode() followed by htmlentities() again can lead to nested entities like &amp;amp;. To avoid this, ensure your encoding pipeline is linear: encode once for transport (urlencode), decode once upon receipt (urldecode), and only re-encode for display if necessary.

If you are working within the Laravel ecosystem, which offers robust tools for handling these scenarios, you might encounter Illuminate\Support\Str::safeUrl() or similar utilities depending on the version, but sticking to core PHP functions like urlencode() remains the most portable and predictable approach for raw query string manipulation unless a framework-specific helper is explicitly designed to handle your specific edge cases. For more complex routing needs where strict validation is required, consider utilizing Laravel's built-in routing features which can parse request data into distinct variables without manual string concatenation.

Ultimately, the choice between urlencode() and manual replacement depends on whether you are constructing a URL programmatically or merely sanitizing input. Always validate that your input matches expected patterns before encoding to prevent unexpected behavior with malformed characters that might not represent valid UTF-8 sequences.

Our network