Module 25: File HandlingIntermediate45 min read
File Handling, Locking (flock) & Secure File Upload Architecture
Read/write files safely, prevent race conditions with flock(), block path traversal (../), and validate uploaded files by MIME type and random filenames.
Key Takeaways & Core Concepts
- Path Traversal Prevention: Never pass raw
$_GET['file']intofopen()orinclude(); usebasename()and an allowlist! - Upload Security: Check
$_FILES['f']['error'] === UPLOAD_ERR_OK, verify real MIME type withfinfo_file(), generate a random UUID filename, and store uploads outside the public webroot.
File Handling, Locking (flock) & Secure File Upload Architecture
### 1. Safe Filesystem & Upload Rules
- Path Traversal Prevention: Never pass raw
$_GET['file']intofopen()orinclude(); usebasename()and an allowlist! - Upload Security: Check
$_FILES['f']['error'] === UPLOAD_ERR_OK, verify real MIME type withfinfo_file(), generate a random UUID filename, and store uploads outside the public webroot.
1. Path Traversal Sanitization with basename()
1<?php
2$userInput = "../../etc/passwd";
3$safeName = basename($userInput);
4echo "Sanitized filename: $safeName\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
4 lines
Note: `basename()` strips directory traversal prefixes like `../../`.
Practice & AssessmentPHP Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)