# 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.

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

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Reject Uploads That Contain PHP Code" 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/
