• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JayBizzle / Crawler-Detect / 43484817713

13 Nov 2026 06:39PM UTC coverage: 96.429% (-3.6%) from 100.0%
43484817713

push

github

web-flow
Add a way to contribute real browser user agents (#653)

Adds an issue form for batches of User-Agents from real visitor traffic,
a section in CONTRIBUTING.md and the README describing the format, and
an import script (composer import-devices) that dedupes a submission,
pulls Sec-CH-UA out of any client hints, and lists anything CrawlerDetect
flags instead of adding it.

54 of 56 relevant lines covered (96.43%)

23.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.36
/src/CrawlerDetect.php
1
<?php
2

3
/*
4
 * This file is part of Crawler Detect - the web crawler detection library.
5
 *
6
 * (c) Mark Beech <m@rkbee.ch>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11

12
namespace Jaybizzle\CrawlerDetect;
13

14
use Jaybizzle\CrawlerDetect\Fixtures\AbstractProvider;
15
use Jaybizzle\CrawlerDetect\Fixtures\Crawlers;
16
use Jaybizzle\CrawlerDetect\Fixtures\Exclusions;
17
use Jaybizzle\CrawlerDetect\Fixtures\Headers;
18

19
class CrawlerDetect
20
{
21
    /**
22
     * The user agent.
23
     *
24
     * @var string|null
25
     */
26
    protected $userAgent;
27

28
    /**
29
     * Headers that contain a user agent.
30
     *
31
     * @var array
32
     */
33
    protected $httpHeaders = [];
34

35
    /**
36
     * Store regex matches.
37
     *
38
     * @var array
39
     */
40
    protected $matches = [];
41

42
    /**
43
     * Crawlers object.
44
     *
45
     * @var \Jaybizzle\CrawlerDetect\Fixtures\Crawlers
46
     */
47
    protected $crawlers;
48

49
    /**
50
     * Exclusions object.
51
     *
52
     * @var \Jaybizzle\CrawlerDetect\Fixtures\Exclusions
53
     */
54
    protected $exclusions;
55

56
    /**
57
     * Headers object.
58
     *
59
     * @var \Jaybizzle\CrawlerDetect\Fixtures\Headers
60
     */
61
    protected $uaHttpHeaders;
62

63
    /**
64
     * The compiled regex string.
65
     *
66
     * @var string
67
     */
68
    protected $compiledRegex;
69

70
    /**
71
     * The compiled exclusions regex string.
72
     *
73
     * @var string
74
     */
75
    protected $compiledExclusions;
76

77
    /**
78
     * Cache of compiled regex strings keyed by fixture class name, shared
79
     * across instances so per-request `new CrawlerDetect` calls don't
80
     * re-implode the (~1500-entry) pattern list each time.
81
     *
82
     * @var array<string, string>
83
     */
84
    protected static $compileCache = [];
85

86
    /**
87
     * Class constructor.
88
     */
89
    public function __construct(?array $headers = null, $userAgent = null)
90
    {
91
        $this->crawlers = new Crawlers;
31 ✔
92
        $this->exclusions = new Exclusions;
31 ✔
93
        $this->uaHttpHeaders = new Headers;
31 ✔
94

95
        $this->compiledRegex = $this->compileFixtureRegex($this->crawlers);
31 ✔
96
        $this->compiledExclusions = $this->compileFixtureRegex($this->exclusions);
31 ✔
97

98
        $this->setHttpHeaders($headers);
31 ✔
99
        $this->setUserAgent($userAgent);
31 ✔
100
    }
101

102
    /**
103
     * Compile and memoize the regex for a fixture provider.
104
     *
105
     * The pattern list is a fixed class property, so the class name is a
106
     * sufficient cache key — cheaper than hashing the patterns themselves.
107
     *
108
     * @return string
109
     */
110
    protected function compileFixtureRegex(AbstractProvider $fixture)
111
    {
112
        $class = get_class($fixture);
31 ✔
113

114
        if (! isset(self::$compileCache[$class])) {
31 ✔
115
            self::$compileCache[$class] = $this->compileRegex($fixture->getAll());
1 ✔
116
        }
117

118
        return self::$compileCache[$class];
31 ✔
119
    }
120

121
    /**
122
     * Compile the regex patterns into one regex string.
123
     *
124
     * A non-capturing group is used because callers only need the full
125
     * match (preg_match's $matches[0]), not a back-reference.
126
     *
127
     * @param  array  $patterns
128
     * @return string
129
     */
130
    public function compileRegex($patterns)
131
    {
132
        return '(?:'.implode('|', array_map([$this, 'boundOpenPrefix'], $patterns)).')';
2 ✔
133
    }
134

135
    /**
136
     * Stop a pattern with an open-ended prefix from being retried at every
137
     * character of the same token.
138
     *
139
     * The catch-all starts with '[a-z0-9\-_]*' so that getMatches() returns
140
     * the whole name ('somenaughtybot') and not just the keyword. Unanchored,
141
     * the engine attempts it from each position in a run of those characters
142
     * and rescans the rest of the run every time, which is quadratic in the
143
     * length of the run. Without the PCRE JIT a few kilobytes of filler in a
144
     * header costs seconds.
145
     *
146
     * Requiring that the prefix starts at the beginning of a token makes it
147
     * linear. The leftmost match was always at the start of the token anyway,
148
     * so results and getMatches() are unchanged.
149
     *
150
     * This is applied here and not in the fixture because the exported
151
     * patterns are used by ports whose regex engines have no lookbehind.
152
     *
153
     * @param  string  $pattern
154
     * @return string
155
     */
156
    protected function boundOpenPrefix($pattern)
157
    {
158
        if (strpos($pattern, '[a-z0-9\-_]*') === 0) {
2 ✔
159
            return '(?<![a-z0-9\-_])'.$pattern;
1 ✔
160
        }
161

162
        return $pattern;
2 ✔
163
    }
164

165
    /**
166
     * Set HTTP headers.
167
     *
168
     * Accepts either the _SERVER-style names PHP's SAPI produces
169
     * (HTTP_USER_AGENT) or the real header names carried by a PSR-7 request,
170
     * HttpFoundation, Swoole or a Lambda event ('User-Agent'). Both are stored
171
     * under the canonical HTTP_ form so lookups stay uniform.
172
     *
173
     * @param  array|null  $httpHeaders
174
     */
175
    public function setHttpHeaders($httpHeaders = null)
176
    {
177
        // Use global _SERVER if $httpHeaders aren't defined.
178
        if (! is_array($httpHeaders) || ! count($httpHeaders)) {
31 ✔
179
            $httpHeaders = $_SERVER;
31 ✔
180
        }
181

182
        // Clear existing headers.
183
        $this->httpHeaders = [];
31 ✔
184

185
        $uaHeaders = array_flip(
31 ✔
186
            array_map([$this, 'normaliseHeaderName'], $this->getUaHttpHeaders())
31 ✔
187
        );
31 ✔
188

189
        // Only save HTTP headers. In PHP land, that means _SERVER vars that
190
        // start with HTTP_ — plus, for non-SAPI sources, any key whose real
191
        // header name is one we actually read.
192
        foreach ($httpHeaders as $key => $value) {
31 ✔
193
            $name = $this->normaliseHeaderName($key);
31 ✔
194

195
            if (strpos(strtoupper((string) $key), 'HTTP_') === 0 || isset($uaHeaders[$name])) {
31 ✔
196
                $this->httpHeaders['HTTP_'.$name] = $this->normaliseHeaderValue($value);
10 ✔
197
            }
198
        }
199
    }
200

201
    /**
202
     * Reduce a header name to its canonical form - uppercased, underscore
203
     * separated, with any SAPI 'HTTP_' prefix removed.
204
     *
205
     * @param  string  $key
206
     * @return string
207
     */
208
    protected function normaliseHeaderName($key)
209
    {
210
        $key = strtoupper((string) $key);
31 ✔
211

212
        // Strip the prefix before folding hyphens, so only a genuine
213
        // underscore-separated SAPI key loses it. A real header named
214
        // 'Http-User-Agent' must not be mistaken for the user agent.
215
        if (strpos($key, 'HTTP_') === 0) {
31 ✔
216
            $key = substr($key, 5);
31 ✔
217
        }
218

219
        return str_replace('-', '_', $key);
31 ✔
220
    }
221

222
    /**
223
     * Flatten a header value. PSR-7 and HttpFoundation both expose values as
224
     * an array of strings, where the SAPI gives a single pre-joined string.
225
     *
226
     * @param  mixed  $value
227
     * @return string
228
     */
229
    protected function normaliseHeaderValue($value)
230
    {
231
        return is_array($value) ? implode(', ', $value) : (string) $value;
10 ✔
232
    }
233

234
    /**
235
     * Return user agent headers.
236
     *
237
     * @return array
238
     */
239
    public function getUaHttpHeaders()
240
    {
241
        return $this->uaHttpHeaders->getAll();
31 ✔
242
    }
243

244
    /**
245
     * Set the user agent.
246
     *
247
     * @param  string|null  $userAgent
248
     */
249
    public function setUserAgent($userAgent = null)
250
    {
251
        if (is_null($userAgent)) {
31 ✔
252
            $userAgent = '';
31 ✔
253

254
            foreach ($this->getUaHttpHeaders() as $altHeader) {
31 ✔
255
                if (isset($this->httpHeaders[$altHeader])) {
31 ✔
256
                    $userAgent .= $this->httpHeaders[$altHeader].' ';
10 ✔
257
                }
258
            }
259

260
            // If no headers were found, keep it as null.
261
            if ($userAgent === '') {
31 ✔
262
                $userAgent = null;
31 ✔
263
            }
264
        }
265

266
        return $this->userAgent = $userAgent;
31 ✔
267
    }
268

269
    /**
270
     * Check user agent string against the regex.
271
     *
272
     * @param  string|null  $userAgent
273
     * @return bool
274
     */
275
    public function isCrawler($userAgent = null)
276
    {
277
        $this->matches = [];
25 ✔
278

279
        $agent = preg_replace(
25 ✔
280
            "/{$this->compiledExclusions}/i",
25 ✔
281
            '',
25 ✔
282
            $userAgent ?: $this->userAgent ?: ''
25 ✔
283
        );
25 ✔
284

285
        if ($agent === null || trim($agent) === '') {
25 ✔
286
            return false;
4 ✔
287
        }
288

289
        $agent = trim($agent);
23 ✔
290

291
        $result = preg_match("/{$this->compiledRegex}/i", $agent, $this->matches);
23 ✔
292

293
        if ($result === false) {
23 ✔
294
            $this->matches = [];
×
295

296
            return false;
×
297
        }
298

299
        return (bool) $result;
23 ✔
300
    }
301

302
    /**
303
     * Return the matches.
304
     *
305
     * @return string|null
306
     */
307
    public function getMatches()
308
    {
309
        return isset($this->matches[0]) ? $this->matches[0] : null;
6 ✔
310
    }
311

312
    /**
313
     * @return string|null
314
     */
315
    public function getUserAgent()
316
    {
317
        return $this->userAgent;
2 ✔
318
    }
319
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc