Detect if the user agent is a bot and act upon it. The detection is based on the bot list from matomo-org/device-detector, which is compiled into a single regular expression and updated weekly.
Before the full bot list is used, the user agent is checked against a short list of the most active crawlers (search engines, AI crawlers, SEO tools and social media fetchers). This makes it much faster to detect the most common bots and hence speeds up your request cycle.
- PHP 8.1 or higher
- Symfony 6.4, 7.4 or 8
composer require setono/bot-detection-bundleIf you use Symfony Flex, the bundle is enabled automatically. Otherwise, add it to config/bundles.php:
<?php
return [
// ...
Setono\BotDetectionBundle\SetonoBotDetectionBundle::class => ['all' => true],
];Inject BotDetectorInterface:
<?php
use Setono\BotDetectionBundle\BotDetector\BotDetectorInterface;
final class YourService
{
public function __construct(private readonly BotDetectorInterface $botDetector)
{
}
public function yourAction(string $userAgent): void
{
// Checks the user agent of the current main request
if ($this->botDetector->isBotRequest()) {
// do something to this bot!
}
// Checks a user agent string
if ($this->botDetector->isBot($userAgent)) {
// ...
}
}
}isBotRequest() also accepts a Request object. It returns false if there is no request or the request has no
User-Agent header.
{% if is_bot_request() %}
I knew you were a bot!
{% endif %}
{% if is_bot(user_agent) %}
This user agent is a bot
{% endif %}The list of the most active crawlers is the setono_bot_detection.popular_bots parameter. You can override it in
config/services.yaml, e.g. to put the bots that visit your site the most first:
parameters:
setono_bot_detection.popular_bots:
- Googlebot
- bingbot
- MyCustomCrawlerEach entry is a regular expression that is matched case-insensitively against the user agent. A user agent that matches an entry is treated as a bot, so keep the entries specific. A user agent that doesn't match any of them is still checked against the full bot list.