Sanitizing strings to make them URL and filename safe?

Sanitizing strings to make them URL and filename safe?

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

Stefan Bogdanescu

Founder & Senior Architect

Sanitizing Strings for URLs and Filenames: A Critical Look at Regex Logic

When building applications that handle user-generated content, you inevitably face the need to normalize strings. Whether creating a blog post slug from a title or renaming an uploaded file to avoid directory traversal attacks, the goal is identical: strip dangerous characters while preserving readability. The challenge lies in balancing strict security with internationalization support for non-ASCII characters.

Consider the following logic used to generate safe identifiers:

function sanitize($string = '', $is_filename = false) {
    // Replace all weird characters with dashes
    $string = preg_replace('/[^\w\-'. ($is_filename ? '~_\.' : ''). ']+/u', '-', $string);

    // Only allow one dash separator at a time (and make string lowercase)
    return mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8');
}

This approach attempts to solve two distinct problems: URL safety and filename safety. The core mechanism relies on a negative character class regex, [^\w\-...], which effectively acts as a filter. It identifies any character that is not a word character (alphanumeric or underscore), not a dash, and optionally not a tilde, underscore, or dot if $is_filename is true. These unwanted characters are replaced with dashes.

However, relying solely on regex substitution introduces subtle pitfalls regarding path traversal and edge cases in operating system file systems.

The Hidden Danger of Path Traversal

The most critical oversight in string sanitization for filenames is the lack of explicit handling for dot-prefixes and dot-suffixes. While your regex replaces "weird characters" with dashes, it does not remove standalone dots or sequences that could create parent directory references.

In a Linux environment, ../ is the gateway to directory traversal. If a user uploads a file named ../../etc/passwd, your current logic might replace non-word characters but leave the dots intact if they are considered "safe" by your specific character class definition. Even worse, filenames like .htaccess or ..git can inadvertently expose sensitive server configurations if not stripped or sanitized before storage.

To truly secure filenames, you must explicitly remove leading and trailing slashes as well as any path separators. Additionally, stripping the filename component from a full path string is a mandatory step before sanitization. If the input is /path/to/../../sensitive, simply replacing characters won't stop an attacker from navigating up the tree if the file system implementation doesn't strictly enforce canonical paths during write operations.

Internationalization and Readability

Your use of mb_strtolower with 'UTF-8' is a strong start, acknowledging that slugs should be lowercase for consistency across different operating systems (Windows often treats case-insensitively, while Linux distinguishes them). However, the regex /[^\w...] defines \w based on Unicode properties depending on the PHP version and PCRE configuration.

In modern PHP versions, \w includes non-ASCII letters and numbers if the code is running in UTF-8 mode. While this supports international slugs (e.g., converting "Café" to "café"), it can lead to inconsistency if the resulting string contains characters that specific hosting environments or web servers mishandle when generating URLs.

A more robust approach for slugs often involves transliterating non-ASCII characters into their ASCII equivalents before applying the sanitization rules. This ensures that "München" becomes "munich" rather than "münchen", preventing potential encoding issues in older browsers or specific database collations.

Trade-offs and Best Practices

The $is_filename flag adds flexibility, allowing temporary files like ~vim.swp or file.txt.bak. This is a pragmatic decision for file uploaders, but it requires strict validation on the server side to ensure these temporary files are cleaned up immediately after processing. Leaving them open creates a race condition where an attacker could potentially overwrite critical assets if the cleanup logic is flawed.

Furthermore, do not assume that sanitizing the string name is sufficient protection. You must also sanitize the path component. A filename like ../../shell.sh should be rejected entirely before any regex manipulation occurs. The safest pattern is:

  1. Extract only the basename from the full path provided by the user.
  2. Sanitize the basename using a strict whitelist of allowed characters.
  3. Reject any string containing . that starts with it (hidden files) or ends with it if not part of a valid extension, unless specifically whitelisted.

By combining path normalization with character filtering, you create a defense-in-depth strategy that protects against both injection attacks and file system corruption.

Our network