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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.