# Add a Random Suffix to Uploaded File Names

> Appends a short random string to the name of every uploaded file (for example report-k3f9q2.pdf), so private documents cannot be found by guessing their URL.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: uploads, files, privacy
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/sec-random-upload-file-names/

## Code

```php
// Extensions to rename; leave empty to rename every upload.
$wpide_random_types = array( 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'csv', 'zip', 'txt' );

add_filter( 'wp_handle_upload_prefilter', function ( $file ) use ( $wpide_random_types ) {
    if ( ! empty( $file['error'] ) || empty( $file['name'] ) ) {
        return $file;
    }

    $info = pathinfo( $file['name'] );
    $ext  = isset( $info['extension'] ) ? strtolower( $info['extension'] ) : '';

    if ( $wpide_random_types && ! in_array( $ext, $wpide_random_types, true ) ) {
        return $file;
    }

    $file['name'] = $info['filename'] . '-' . strtolower( wp_generate_password( 6, false ) ) . ( $ext ? '.' . $ext : '' );

    return $file;
} );
```

## Notes

Set $wpide_random_types to limit it to documents if you want image file names to stay clean for SEO.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add a Random Suffix to Uploaded File Names" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
