Best method to generate unique filenames when uploading files PHP

Best method to generate unique filenames when uploading files PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Generating Unique Filenames for File Uploads in PHP

Avoiding duplicate filenames during file uploads is a fundamental requirement for any application handling user-generated content. When two users attempt to upload a file with the same name simultaneously, or when a user retries an upload after a failure, the server must handle these collisions gracefully without overwriting existing data. The most robust strategy involves constructing a new filename that preserves the original file extension while appending a unique identifier to it.

Why Not Rely on Original Names?

Relying solely on the basename() of an uploaded file is risky. While it saves disk space by not storing redundant copies, it introduces significant data integrity risks. If photo.jpg exists and User A tries to upload photo.jpg, a naive implementation will overwrite the original file. This results in immediate data loss for the first user. Furthermore, this approach breaks when multiple users try to upload the exact same image at the same time; one succeeds while the other fails with a generic error message that doesn't indicate why their specific file was rejected.

The Timestamp Approach: Simple but Fragile

The most common initial solution is appending a Unix timestamp to the filename:

$originalName = $_FILES['image']['name'];
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$newFilename = $originalName . '_' . time() . '.' . $extension;
move_uploaded_file($_FILES['image']['tmp_name'], $publicDir . '/' . $newFilename);

This method guarantees uniqueness for the current second because time() returns the current Unix timestamp. However, it is not truly unique across different servers in a load-balanced environment or during clock drift scenarios where multiple servers might share the same second. More importantly, timestamps are predictable. An attacker can easily guess valid filenames within a narrow window if they know the server's approximate time, potentially facilitating denial-of-service attacks by flooding the storage with files that overwrite each other or specific critical resources.

The UUID Strategy: High Entropy and Predictability

A superior alternative is generating a Universally Unique Identifier (UUID). Libraries like Ramsey\Uuid or simple PHP implementations can create 128-bit identifiers that are practically guaranteed to be unique across space and time.

use Ramsey\Uuid\Uuid;

$originalName = $_FILES['image']['name'];
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$uuid = Uuid::uuid4()->toString(); // Generates a UUID v4 (random)
$newFilename = $uuid . '.' . $extension;
move_uploaded_file($_FILES['image']['tmp_name'], $publicDir . '/' . $newFilename);

Using UUIDs ensures that even if thousands of uploads occur in the same millisecond, collisions are statistically impossible. It also removes any time-based predictability from the filename structure. The trade-off is slightly larger filesystem entries and potentially slower directory listings if not handled carefully, though modern filesystems handle 128-bit names without issue.

Handling Original Names in Laravel Ecosystem

If you are working within a Laravel application, the framework provides utilities that simplify this process. You might use Str::random() to generate an alphanumeric string instead of a UUID or timestamp. This offers a balance between uniqueness and readability, though it requires checking availability if you want to preserve the original filename extension logic strictly.

use Illuminate\Support\Str;

$originalName = $_FILES['image']['name'];
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$randomString = Str::random(10); // Generates a random string of 10 characters
$newFilename = $randomString . '.' . $extension;

// Ensure the original name is preserved in metadata if needed, 
// but stored with the new unique filename on disk.
move_uploaded_file($_FILES['image']['tmp_name'], $publicDir . '/' . $newFilename);

Best Practice: Store Metadata Separately

Regardless of whether you choose a timestamp, UUID, or random string, the critical best practice is to never lose the original filename. When a user downloads a file later, they expect vacation-photo.jpg, not a1b2c3d4e5f6.vacation-photo.jpg.

To achieve this, you must store the mapping between the unique disk filename and the original user-provided name in your database. For every upload operation, create a record linking the file ID to both $newFilename and $originalName. This allows your application to serve the file using the generated unique name while presenting the familiar original name to the end-user via HTTP headers or download links.

Conclusion on Implementation

The choice between time(), UUIDs, or random strings depends on your specific threat model and performance requirements. For high-security applications where predictability is a concern, UUIDs are the industry standard. For simpler applications where collision probability within a second is negligible, timestamps remain a valid option. However, all methods must be coupled with database metadata storage to maintain user experience. Always validate file types on the server side before renaming and moving files to prevent malicious content from being stored under seemingly benign names.

Our network