PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?
When you handle file uploads in PHP, $_FILES is your primary interface for metadata about the incoming request. The array structure provides access to the temporary storage location via $_FILES['file']['tmp_name'], as well as the original client-side name through $_FILES['file']['name']. A common friction point arises when you intend to move that uploaded file to a permanent directory or attach it to an email, only to discover the system has replaced the user's chosen filename with a random string like phpvwRGKN.dat.
This behavior is by design. PHP generates these unique, cryptic filenames to prevent collisions if multiple users upload files with identical names simultaneously and to mitigate certain security risks associated with predictable file paths. However, if your application logic requires sending that specific fileâparticularly via emailâthe randomization becomes a functional blocker. You need to retrieve the original filename before moving or processing the file to ensure the recipient sees the expected name in their inbox.
The solution lies in decoupling the storage path from the filename used for display and attachment. When you move a file using move_uploaded_file(), you must explicitly pass both the source path and the destination path. The critical step is constructing that destination path using the original client-provided name rather than letting PHP default to a random one or leaving it blank.
Here is how you can extract and preserve the filename:
$originalName = $_FILES['file']['name'];
$tempPath = $_FILES['file']['tmp_name'];
$destinationDir = '/path/to/uploads/';
$newFileName = $originalName; // Preserve extension and name
// Ensure a safe destination path is constructed
$fullDestination = $destinationDir . $newFileName;
if (move_uploaded_file($tempPath, $fullDestination)) {
// File moved successfully with original name
}
In this snippet, $originalName captures the string sent by the client. By concatenating it directly into the destination path, you override any default behavior that might obscure the filename. This approach respects the user's intent while keeping the file in a secure temporary location until you are ready to finalize its placement.
However, there is a significant trade-off regarding security and filesystem integrity that developers often overlook. While preserving the original name maintains usability, it introduces the risk of path traversal attacks if the input is not sanitized. An attacker could upload a file named ../../etc/passwd or shell.php to execute arbitrary code on your server.
To mitigate this, you must validate the filename against a whitelist of allowed characters and extensions before constructing the final path. You should strip any directory traversal sequences like ../ and ensure the filename consists only of alphanumeric characters, hyphens, underscores, and periods. Additionally, always verify that the file extension matches the MIME type reported by PHP or your validation logic.
// Basic sanitization example
$allowedExtensions = ['doc', 'docx'];
$nameBasename = pathinfo($originalName, PATHINFO_FILENAME);
$nameExt = pathinfo($originalName, PATHINFO_EXTENSION);
if (!in_array(strtolower($nameExt), $allowedExtensions)) {
throw new Exception('Invalid file extension');
}
// Remove directory traversal attempts
$newFileName = basename($originalName);
If you are integrating this logic with email functionality using a library like geekMail, the attachment method typically expects a full local path. Passing the sanitized, original-named path ensures the email client displays the correct filename. Note that some email clients may truncate very long filenames or reject files with certain characters in their names depending on how they handle MIME headers.
For projects built on the Laravel framework, handling this requires accessing the UploadedFile instance provided by the HTTP kernel rather than relying directly on the raw $_FILES superglobal. Laravel's abstraction layer provides methods like getClientOriginalName() and move() which internally manage these details, but understanding the underlying mechanics of $_FILES remains essential for debugging or when writing custom mailers outside the framework's defaults.
