Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

// 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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.