Halloween Sale 15% off Ends in See the plans
PHP

Reject Uploads That Contain PHP Code

Scans every uploaded file that is not a PHP file for hidden PHP code (such as an image with a PHP payload) and refuses the upload if any is found.

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

Code

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

    $handle = fopen( $file['tmp_name'], 'rb' );

    if ( ! $handle ) {
        return $file;
    }

    $chunk = (string) fread( $handle, 2 * MB_IN_BYTES );
    fclose( $handle );

    // "<?=" is only checked in text files: in binary data those three bytes can occur by chance.
    $binary  = (bool) preg_match( '/\.(jpe?g|png|gif|webp|avif|heic|mp[34]|m4a|mov|webm|zip|pdf|docx?|xlsx?|pptx?)$/i', (string) $file['name'] );
    $pattern = $binary ? '/<\?php\b|<script\s+language\s*=\s*["\']?php/i' : '/<\?(php\b|=)|<script\s+language\s*=\s*["\']?php/i';

    if ( preg_match( $pattern, $chunk ) ) {
        $file['error'] = 'This file contains code that is not allowed in uploads.';
    }

    return $file;
}, 5 );

Notes

Only the first 2 MB of each file is scanned to keep uploads fast.

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.