You can block malicious user agents in WordPress using PHP code snippets by checking the $_SERVER['HTTP_USER_AGENT'] value and terminating the request if it matches known bad agents. This method allows you to programmatically deny access to bots or scrapers without modifying server files like .htaccess.
Here is a simple example of PHP code to block specific user agents in WordPress, which you can add to your theme’s functions.php file or a custom plugin:
function block_malicious_user_agents() {
$bad_user_agents = array(
'BadBot',
'EvilScraper',
'SpamBot',
// Add other user agents to block here
);
$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
foreach ($bad_user_agents as $bad_agent) {
if (stripos($user_agent, $bad_agent) !== false) {
// Send 403 Forbidden header and exit
header('HTTP/1.1 403 Forbidden');
exit('Access denied.');
}
}
}
add_action('init', 'block_malicious_user_agents');
Explanation and usage:
- The function
block_malicious_user_agents()runs on WordPress’sinithook, which fires early in the request lifecycle. - It checks the visitor’s user agent string against an array of known malicious user agents.
- If a match is found (case-insensitive), it sends a 403 Forbidden HTTP response and stops further processing.
- You can customize the
$bad_user_agentsarray with the exact user agent strings you want to block.
This PHP-based approach is flexible and does not require server configuration access, unlike .htaccess rules which also can block user agents but need file editing on the server level.
Additional considerations:
- Be careful not to block legitimate user agents (like common browsers or search engine crawlers) to avoid blocking real users.
- Regularly update your list of malicious user agents based on your site’s traffic logs.
- For more robust protection, consider combining PHP blocking with
.htaccessrules or security plugins that offer user agent blocking and other firewall features.
This method provides a straightforward way to block malicious user agents using PHP code snippets in WordPress.










Ang PH Ranking ay nag-aalok ng pinakamataas na kalidad ng mga serbisyo sa website traffic sa Pilipinas. Nagbibigay kami ng iba’t ibang uri ng serbisyo sa trapiko para sa aming mga kliyente, kabilang ang website traffic, desktop traffic, mobile traffic, Google traffic, search traffic, eCommerce traffic, YouTube traffic, at TikTok traffic. Ang aming website ay may 100% kasiyahan ng customer, kaya maaari kang bumili ng malaking dami ng SEO traffic online nang may kumpiyansa. Sa halagang 720 PHP bawat buwan, maaari mong agad pataasin ang trapiko sa website, pagandahin ang SEO performance, at pataasin ang iyong mga benta!
Nahihirapan bang pumili ng traffic package? Makipag-ugnayan sa amin, at tutulungan ka ng aming staff.
Libreng Konsultasyon