Need to safely handle user-provided filenames? This guide covers everything you need to know about filename sanitization via API, including security risks, cross-platform issues, and implementation examples.
Why Sanitize Filenames?
User-provided filenames can contain dangerous characters that cause security vulnerabilities (path traversal), cross-platform issues (invalid characters), or operational problems (special characters in scripts).
For example, ../../../etc/passwd as a filename could traverse directories and overwrite system files if not sanitized.
Dangerous Characters and Patterns
Several types of characters need handling:
Path Traversal
../, ..\, absolute paths (/etc/, C:\) - Allow escaping intended directories.
OS-Specific Invalid Characters
Windows: < > : " / \ | ? *. macOS/Linux: / and null byte.
Reserved Names
Windows: CON, PRN, AUX, NUL, COM1-9, LPT1-9. These cause issues on Windows systems.
Problematic Characters
Spaces at start/end, dots at end, control characters, very long names.
Using the Filename Sanitizer API
TinyFn provides a simple endpoint to sanitize filenames:
POST https://api.tinyfn.io/v1/sanitize/filename
Headers: X-API-Key: your-api-key
Content-Type: application/json
{
"filename": "../../../etc/passwd",
"replacement": "_"
}
{
"original": "../../../etc/passwd",
"sanitized": "etc_passwd",
"changes": [
"Removed path traversal sequences",
"Removed leading dots"
],
"safe": true
}
Parameters
| Parameter | Type | Description |
|---|---|---|
filename |
string | The filename to sanitize |
replacement |
string | Character to replace invalid chars (default: "_") |
maxLength |
integer | Maximum filename length (default: 255) |
preserveExtension |
boolean | Keep file extension when truncating (default: true) |
Code Examples
JavaScript / Node.js
// Sanitize user-uploaded filename
const response = await fetch(
'https://api.tinyfn.io/v1/sanitize/filename',
{
method: 'POST',
headers: {
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
filename: 'user/../../../file.jpg',
replacement: '_'
})
}
);
const { sanitized, safe } = await response.json();
console.log(sanitized); // user_file_name_.jpg
console.log(safe); // true
// Use in file upload handler
async function handleUpload(userFilename) {
const response = await fetch('https://api.tinyfn.io/v1/sanitize/filename', {
method: 'POST',
headers: {
'X-API-Key': 'your-api-key',
'Content-Type': 'application/json'
},
body: JSON.stringify({ filename: userFilename })
});
const { sanitized } = await response.json();
return `uploads/${sanitized}`;
}
Python
import requests
# Sanitize dangerous filename
response = requests.post(
'https://api.tinyfn.io/v1/sanitize/filename',
json={
'filename': 'CON.txt', # Reserved on Windows
'replacement': '_'
},
headers={'X-API-Key': 'your-api-key'}
)
data = response.json()
print(data['sanitized']) # _CON.txt or similar
print(data['changes']) # ['Prefixed reserved name']
# Sanitize with length limit
response = requests.post(
'https://api.tinyfn.io/v1/sanitize/filename',
json={
'filename': 'a' * 300 + '.pdf',
'maxLength': 100,
'preserveExtension': True
},
headers={'X-API-Key': 'your-api-key'}
)
print(len(response.json()['sanitized'])) # 100 (including .pdf)
cURL
# Sanitize filename
curl -X POST "https://api.tinyfn.io/v1/sanitize/filename" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"filename": "../../../etc/passwd", "replacement": "_"}'
# Sanitize with options
curl -X POST "https://api.tinyfn.io/v1/sanitize/filename" \
-H "X-API-Key: your-api-key" \
-H "Content-Type: application/json" \
-d '{"filename": "file.txt", "maxLength": 50, "preserveExtension": true}'
Common Use Cases
- File Uploads: Sanitize user-provided filenames before saving
- Download Handlers: Clean filenames for Content-Disposition headers
- Backup Systems: Ensure backup filenames are valid across platforms
- Export Features: Generate safe filenames for exported files
- CMS Systems: Clean uploaded media filenames
Best Practices
- Always sanitize server-side: Never trust client input
- Use UUID/hash as alternative: Consider not using user-provided names at all
- Limit length: Different file systems have different limits
- Test cross-platform: Ensure files work on Windows, macOS, and Linux
- Log original names: Keep record of original filename separately
Try the Filename Sanitizer API
Get your free API key and start sanitizing filenames in seconds.
Get Free API Key