Halloween Sale 15% off Ends in See the plans
PHP

Block Malicious Request Patterns

A tiny firewall that returns 403 Forbidden for URLs containing typical attack strings, such as directory traversal, SQL injection and PHP stream wrappers.

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

Code

// Patterns checked against the decoded URL (path and query string).
$wpide_firewall_patterns = array(
    '#\.\./#',
    '#(?:/|%2f)etc/passwd#i',
    '#(?:php|phar|zip|data|expect)://#i',
    '#union(?:\s|\+|/\*.*\*/)+(?:all(?:\s|\+)+)?select#i',
    '#\b(?:base64_decode|eval|assert|shell_exec|passthru|system)\s*\(#i',
    '#<\s*script#i',
    '#(?:GLOBALS|_REQUEST|_SERVER)\s*\[#',
    '#wp-config\.php#i',
);

add_action( 'init', function () use ( $wpide_firewall_patterns ) {
    if ( empty( $_SERVER['REQUEST_URI'] ) || ( is_user_logged_in() && current_user_can( 'unfiltered_html' ) ) ) {
        return;
    }

    $uri = rawurldecode( rawurldecode( (string) wp_unslash( $_SERVER['REQUEST_URI'] ) ) );

    foreach ( $wpide_firewall_patterns as $pattern ) {
        if ( preg_match( $pattern, $uri ) ) {
            status_header( 403 );
            nocache_headers();
            exit( 'Forbidden' );
        }
    }
}, 0 );

Notes

Form submissions are not inspected, so editors keep working, and it complements rather than replaces a real web application firewall.

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.