Alert When PHP Files Appear in the Uploads Folder
Scans the uploads folder once a day for PHP files, which never belong there and usually mean a backdoor, and emails the administrator and shows a dashboard warning when new ones show up.
Opens WPIDE on
Code
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_uploads_php_scan' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpide_uploads_php_scan' );
}
} );
add_action( 'wpide_uploads_php_scan', function () {
$uploads = wp_get_upload_dir();
$base = $uploads['basedir'];
$found = array();
if ( ! is_dir( $base ) ) {
return;
}
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base, FilesystemIterator::SKIP_DOTS ) );
foreach ( $files as $file ) {
if ( ! $file->isFile() || ! preg_match( '/\.(php\d?|phtml|phar|pht)$/i', $file->getFilename() ) ) {
continue;
}
if ( 'index.php' === strtolower( $file->getFilename() ) && $file->getSize() < 200 ) {
continue;
}
$found[] = str_replace( $base, '', $file->getPathname() );
if ( count( $found ) >= 100 ) {
break;
}
}
$previous = (array) get_option( 'wpide_uploads_php_found', array() );
update_option( 'wpide_uploads_php_found', $found, false );
$new = array_diff( $found, $previous );
if ( $new ) {
wp_mail(
get_option( 'admin_email' ),
sprintf( '[%s] PHP files found in uploads', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
"These PHP files were found in your uploads folder, where PHP files should never be:\n\n" . implode( "\n", $new ) . "\n\nCheck and remove them."
);
}
} );
add_action( 'admin_notices', function () {
$found = (array) get_option( 'wpide_uploads_php_found', array() );
if ( $found && current_user_can( 'manage_options' ) ) {
printf( '<div class="notice notice-error"><p>%s</p></div>', esc_html( sprintf( 'Security: %d PHP file(s) found in the uploads folder, for example %s. Check and remove them.', count( $found ), $found[0] ) ) );
}
} );
Notes
Small "silence is golden" index.php files that some plugins add are ignored.
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.