Course contentsShow
← Security
Lesson 985 of 3,05220. Web Security - File Upload and ProcessingFree lesson

Filename Sanitization and Generation

Generate random filenames, sanitize user input, prevent directory traversal, and store original names separately in metadata.

Filename Sanitization and Generation

What you'll learn: How to safely handle user-provided filenames by sanitizing input and generating random names to prevent directory traversal and system attacks.

The Core Problem

When users upload files, they control the filename—and malicious users exploit this. A filename like ../../etc/passwd could traverse directories, shell.php.jpg might bypass filters, or names with special characters (\0, <, >) could break filesystem operations or trigger vulnerabilities.

The Two-Part Solution

1. Generate Random Filenames

Never trust user-provided filenames for storage. Generate a secure random identifier instead:

Original: "my-vacation-photo.jpg"
Stored as: "7f3a9c8b-e2d4-4a1f-9b6c-1e5d8a3f7c2e.jpg"

Use cryptographically secure random generators (UUIDs, random tokens) so attackers cannot predict filenames—preventing direct access attacks.

2. Store Original Names in Metadata

Users still want meaningful names. Store the original filename separately in a database or metadata file:

File on disk: 7f3a9c8b-e2d4-4a1f-9b6c-1e5d8a3f7c2e.jpg
Database record:
  - generated_name: "7f3a9c8b-e2d4-4a1f-9b6c-1e5d8a3f7c2e.jpg"
  - original_name: "my-vacation-photo.jpg"
  - upload_date: 2024-01-15

When serving downloads, present the original name to users—but the filesystem only knows the sanitized random name.

Why This Works

Think of it like a coat check: you hand over your jacket (original filename), receive a random ticket number (generated name), and the system tracks which ticket maps to which jacket. Even if someone tries to submit a malicious "ticket," they can't access other people's coats.

This approach eliminates directory traversal (no ../), prevents extension confusion, avoids filename collisions, and stops attackers from guessing file locations.

Key Takeaway:
Always generate random filenames for storage, never use user input directly, and preserve original names only in secure metadata—this separates what users see from what the filesystem processes.