PHPackages                             hk2/sanitize-search - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. hk2/sanitize-search

ActiveMagento2-module[Validation &amp; Sanitization](/categories/validation)

hk2/sanitize-search
===================

Magento 2 extension to sanitize harmful SQL keywords from search queries

v1.0.0(4w ago)011OSL-3.0PHPPHP ^8.1 || ^8.2 || ^8.3 || ^8.4CI passing

Since May 12Pushed 4w agoCompare

[ Source](https://github.com/basantmandal/magento2-search-sanitizer-module)[ Packagist](https://packagist.org/packages/hk2/sanitize-search)[ RSS](/packages/hk2-sanitize-search/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (2)Versions (2)Used By (0)

 [![Version](https://camo.githubusercontent.com/ea9ef426d7257249967444fc38f23d854e483b614a19030e12feb17fa0bb5ff5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75653f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/ea9ef426d7257249967444fc38f23d854e483b614a19030e12feb17fa0bb5ff5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75653f7374796c653d666c61742d737175617265) [![Magento](https://camo.githubusercontent.com/cc7afc3a994043bd5e1bbe18fdecdf4377481f03e2dc7a05728c3174c7da66bf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d6167656e746f2d322e342e782d6639373331363f7374796c653d666c61742d737175617265266c6f676f3d6d6167656e746f266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/cc7afc3a994043bd5e1bbe18fdecdf4377481f03e2dc7a05728c3174c7da66bf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d6167656e746f2d322e342e782d6639373331363f7374796c653d666c61742d737175617265266c6f676f3d6d6167656e746f266c6f676f436f6c6f723d7768697465) [![PHP](https://camo.githubusercontent.com/2f2d39f30d9a245b748ead3268e5de0819ddab6c31a393904a4f33652b504e79/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3763336165643f7374796c653d666c61742d737175617265266c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://camo.githubusercontent.com/2f2d39f30d9a245b748ead3268e5de0819ddab6c31a393904a4f33652b504e79/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e322532422d3763336165643f7374796c653d666c61742d737175617265266c6f676f3d706870266c6f676f436f6c6f723d7768697465) [![License](https://camo.githubusercontent.com/a3fd2257982f64afbde00a66a8ab5984ee3f6e176f00eb2ec4ea61d862bc113b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4f534c2d2d332e302d677265656e3f7374796c653d666c61742d737175617265)](https://camo.githubusercontent.com/a3fd2257982f64afbde00a66a8ab5984ee3f6e176f00eb2ec4ea61d862bc113b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4f534c2d2d332e302d677265656e3f7374796c653d666c61742d737175617265) [![Packagist](https://camo.githubusercontent.com/6ede67abdce9a97ea56a62b65a1d7f5e8ae0fc4ad4c3387def61f2815466036a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686b322f73616e6974697a652d7365617263683f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hk2/sanitize-search)
 [![Website](https://camo.githubusercontent.com/48510337f411c7e193a31e9bdb6802d49664918dac999471dcc705c9a94fa031/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f576562736974652d3030303f7374796c653d666c61742d737175617265266c6f676f3d6b6f2d6669266c6f676f436f6c6f723d7768697465)](https://www.basantmandal.in/) [![LinkedIn](https://camo.githubusercontent.com/f47f622117d99af4d0fcba939449e0949d2301d48601b78a25b6e7e1cf580d3e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c696e6b6564496e2d3041363643323f7374796c653d666c61742d737175617265266c6f676f3d6c696e6b6564696e266c6f676f436f6c6f723d7768697465)](https://www.linkedin.com/in/basantmandal/) [![Email](https://camo.githubusercontent.com/4fb7fe62859d942d68ae2f48af7c8fb6165e8f1dc236fa5bbc970e01efff28ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f456d61696c2d737570706f7274253430626173616e746d616e64616c2e696e2d626c75653f7374796c653d666c61742d737175617265266c6f676f3d676d61696c)](mailto:support@basantmandal.in)

HK2 Sanitize Search — Magento 2 Search Query Sanitizer
======================================================

[](#hk2-sanitize-search--magento-2-search-query-sanitizer)

**HK2 SanitizeSearch** is a lightweight Magento 2 module that sanitizes user-submitted search queries by stripping harmful SQL keywords and characters. It hooks into `Magento\Search\Model\QueryFactory` via a `beforeCreate` plugin, applies a regex filter, and logs sanitization events to a dedicated log file for auditing.

📄 Overview
----------

[](#-overview)

The module acts as a defense-in-depth layer against SQL injection attempts entering through the storefront search box. It removes SQL control keywords (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `DROP`, `UNION`), statement terminators (`;`), and comment markers (`--`, `#`) from user input before it reaches the search pipeline. Clean queries pass through with zero overhead.

🧠 Problem Statement
-------------------

[](#-problem-statement)

Magento's native search accepts arbitrary user input and feeds it into the search query pipeline. While Magento uses prepared statements and proper ORM practices, an unsanitized search box represents an unnecessary attack surface. Malicious actors can probe the system by submitting search strings containing SQL control characters and keywords (e.g., `SELECT`, `UNION`, `;`, `--`).

Security best practices dictate that user input should be sanitized at every trust boundary. The search input field — accessible to any visitor — is a clear trust boundary that benefits from proactive sanitization.

💡 Solution Approach
-------------------

[](#-solution-approach)

A plugin intercepts the `beforeCreate` method of `Magento\Search\Model\QueryFactory` and applies a `preg_replace` to remove dangerous patterns from the raw query string:

- SQL keywords: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `DROP`, `UNION` (case-insensitive)
- Statement terminator: `;`
- SQL comment markers: `--` and `#`

If any content is stripped, the event is logged to `var/log/sanitizer.log` at WARNING level. The sanitizer can be toggled on/off via admin configuration at **Stores &gt; Configuration &gt; HK2 &gt; Search Sanitizer**.

🆚 Alternatives Considered
-------------------------

[](#-alternatives-considered)

ApproachWhy not chosen**Prepared statement reliance only**Places full trust in the ORM layer; no defense-in-depth at the input boundary**Full input validation/whitelisting**Too restrictive; would break legitimate search queries with special characters**WAF-level filtering**Requires external infrastructure; adds latency; harder to audit**Escaping instead of stripping**Escaped SQL keywords may still appear suspicious in logs or trigger false alarms**Third-party security module**Heavy dependency; most include far more than search sanitizationStripping is chosen as a minimal, predictable operation — it removes known dangerous patterns without altering the shape of legitimate queries.

👥 Who is this for?
------------------

[](#-who-is-this-for)

- **Magento 2 store owners** hardening their storefront against SQL injection probes
- **Security-conscious developers** needing a zero-dependency, auditable sanitization layer
- **Agencies and system integrators** deploying sites that must pass security compliance reviews
- **Merchants in regulated industries** (finance, healthcare, e-commerce) with customer data behind the search interface

🎯 Use Cases
-----------

[](#-use-cases)

1. **E-commerce stores** — prevent SQL injection attempts through the product search box
2. **Multi-tenant Magento installations** — a vulnerability in one tenant's code could be probed via search
3. **Compliance-driven environments** — satisfying audit requirements for input sanitization at all user entry points
4. **Staging/demo sites** — quickly add a security layer without modifying core or installing a full security suite
5. **Custom search implementations** — where `Magento\Search\Model\QueryFactory` is still part of the pipeline

✨ Key Features
--------------

[](#-key-features)

- **SQL keyword stripping** — removes `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `DROP`, `UNION`, `;`, `--`, and `#` from search queries (case-insensitive)
- **Dedicated logging** — every sanitization event is recorded to `var/log/sanitizer.log` at WARNING level with original and sanitized values
- **Configurable enable/disable** — toggle via Stores &gt; Configuration &gt; HK2 &gt; Search Sanitizer
- **Defense-in-depth** — complements Magento's ORM and prepared statements with input-level sanitization
- **Zero impact on clean queries** — queries without harmful patterns pass through unmodified
- **Lightweight** — single plugin, no database schemas, no API endpoints, no console commands

🏗️ Architecture Overview
------------------------

[](#️-architecture-overview)

```
┌─────────────────────────────────────────────────────────────────────────┐
│  Storefront search form                                                │
│  User submits:  "product; DROP TABLE customers; --"                    │
└──────────────────────────┬──────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────────────────┐
│  Magento\Search\Model\QueryFactory::beforeCreate                       │
│  (Plugin: HK2\SanitizeSearch\Plugin\SearchSanitizer)                   │
│                                                                         │
│  1. Check config flag (hk2_sanitizesearch/general/enabled)             │
│  2. If disabled → return original query unchanged                       │
│  3. If enabled:                                                         │
│     a. preg_replace(/(select|insert|update|delete|drop|union|;|--|#)/i) │
│     b. trim()                                                           │
│     c. If changed → log original + sanitized to Monolog (WARNING)      │
│     d. Return sanitized query                                           │
└─────────────────────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────────────────────┐
│  Normal Magento search pipeline                                        │
│  (Query, search results, etc.)                                          │
└─────────────────────────────────────────────────────────────────────────┘

Logging (when change detected):
    HK2\SanitizeSearch\Logger\Logger (custom Monolog channel)
        └── HK2\SanitizeSearch\Logger\Handler (writes to var/log/sanitizer.log, WARNING level)

```

### Key files

[](#key-files)

FileRole`Plugin/SearchSanitizer.php`Plugin intercepting `QueryFactory::beforeCreate``Logger/Logger.php`Custom Monolog logger class`Logger/Handler.php`Log handler writing to `var/log/sanitizer.log``etc/di.xml`Plugin registration and logger wiring`etc/module.xml`Module declaration sequencing on `HK2_Core``etc/adminhtml/system.xml`Admin system configuration under HK2 tab`etc/adminhtml/menu.xml`Admin menu entry under Content📋 System Requirements
---------------------

[](#-system-requirements)

- **Magento**: 2.4.x (Open Source / Adobe Commerce)
- **PHP**: ^8.1 || ^8.2 || ^8.3 || ^8.4
- **Composer**: 2.x
- **Dependencies**: `hk2/core` ^1.0, `magento/framework` ^103.0.0
- **No database modifications** — operates entirely at the PHP plugin layer

🚀 Installation
--------------

[](#-installation)

```
composer require hk2/sanitize-search
```

```
bin/magento module:enable HK2_SanitizeSearch
bin/magento setup:upgrade
bin/magento cache:clean
```

Verify:

```
bin/magento module:status HK2_SanitizeSearch
```

⚙️ Configuration
----------------

[](#️-configuration)

Navigate to **Stores &gt; Configuration &gt; HK2 &gt; Search Sanitizer** (or **Content &gt; Search Sanitizer** from the admin menu).

SettingDescription**Enable Search Sanitization**Set to **Yes** to enable SQL keyword stripping. Set to **No** to pass all queries through unchanged.**Default**: No (disabled). Ships disabled so operators can enable after testing.

Configuration path: `hk2_sanitizesearch/general/enabled`

🔒 Content Security Policy (CSP)
-------------------------------

[](#-content-security-policy-csp)

This module does **not** modify Magento's CSP headers or `csp_whitelist.xml`. It operates exclusively at the server-side PHP layer before the search query enters the ORM pipeline.

HK2 SanitizeSearch complements CSP in a holistic security strategy: CSP prevents malicious scripts from executing in the browser, while search sanitization prevents malicious SQL patterns from entering the database pipeline.

🚀 Production Readiness
----------------------

[](#-production-readiness)

This module is production-ready and has been designed with the following considerations:

- **Zero database schema changes** — no setup patch, no SQL install/upgrade scripts, no data patches
- **Zero API surface** — no REST, GraphQL, or SOAP endpoints to secure
- **Minimal performance impact** — a single `preg_replace` on the search query string; disabled by default
- **Configurable at runtime** — toggle via admin configuration without code deployment
- **Defense-in-depth** — complements existing Magento security layers rather than replacing them
- **Auditable** — all sanitization events are logged with original and sanitized values for forensic review

Enable on staging first, test with your store's typical search patterns, then enable in production.

🔐 Privacy &amp; GDPR
--------------------

[](#-privacy--gdpr)

- **No personal data collection** — the module does not track, store, or transmit user identities, IP addresses, or session data
- **Log contents** — the only persisted data is the original and sanitized query string (written to `var/log/sanitizer.log` at WARNING level)
- **Log retention** — standard Magento log rotation applies; configure per your data protection obligations
- **No third-party services** — the module makes no external network calls and sends no data off-server
- **Recommended actions**: review log retention for `var/log/sanitizer.log`, consider disabling query logging if searches may contain PII, include sanitization logging in your data processing register

🧪 Testing Strategy
------------------

[](#-testing-strategy)

Test caseInputExpected outputClean query`laptop``laptop` (unchanged, no log)SQL keyword`SELECT * FROM users``* FROM users` (logged)Statement terminator`admin'; DELETE``admin''` (logged)Comment marker`password-- comment``password comment` (logged)Hash comment`admin#foo``adminfoo` (logged)Mixed case`UnIoN Select 1``1` (logged)Multiple keywords`DROP;SELECT;UPDATE``` (empty, logged)Disabled moduleany input with config disabledunchanged, no logEmpty input```` (no error)**Recommended approach**: enable on a staging environment first, submit various test queries, and inspect `var/log/sanitizer.log` before enabling in production.

No automated test suite ships with the module.

📚 Documentation
---------------

[](#-documentation)

Additional documentation is available in the `docs/` directory:

- [Installation Guide](docs/installation.md)
- [Usage Guide](docs/usage.md)
- [Compatibility Matrix](docs/compatibility.md)

⚠️ Known Limitations
--------------------

[](#️-known-limitations)

1. **Pattern-based, not context-aware** — the regex match removes substrings. "selective" becomes "ive". This is by design: the filter errs on the side of removing potential threats.
2. **Defense-in-depth, not primary SQL protection** — not a substitute for prepared statements, parameterized queries, or proper ORM usage.
3. **No Unicode / multibyte awareness** — non-ASCII homoglyph attacks are not detected.
4. **Log growth** — in high-traffic stores with aggressive probing, the log file may grow quickly.

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome. Please open an issue or pull request on the [GitHub repository](https://github.com/basantmandal/magento2-search-sanitizer-module).

All contributions must adhere to the [Conventional Commits](https://www.conventionalcommits.org/) specification for automated semantic release.

📄 License
---------

[](#-license)

Licensed under the **Open Software License 3.0 (OSL-3.0)**.

The OSL-3.0 is an OSI-approved open source license. It allows you to use, modify, and distribute this software, provided that distributed modifications are made available in source code form.

⚖️ Disclaimer
-------------

[](#️-disclaimer)

This module provides **defense-in-depth** sanitization and is not a replacement for secure coding practices. The author and Basant Mandal are not responsible for any damages or security breaches resulting from the use or misuse of this software. Always follow Magento security best practices, keep your installation up to date, and perform regular security audits.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance94

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

28d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ffa270f1557c4c55c55fec1ad6f2544170980c8dd7f679c10582a3736f7d3a4c?d=identicon)[basantmandal](/maintainers/basantmandal)

---

Top Contributors

[![basantmandal](https://avatars.githubusercontent.com/u/69835601?v=4)](https://github.com/basantmandal "basantmandal (21 commits)")[![semantic-release-bot](https://avatars.githubusercontent.com/u/32174276?v=4)](https://github.com/semantic-release-bot "semantic-release-bot (7 commits)")

---

Tags

magento2HK2magento moduleBasant Mandal

### Embed Badge

![Health badge](/badges/hk2-sanitize-search/health.svg)

```
[![Health](https://phpackages.com/badges/hk2-sanitize-search/health.svg)](https://phpackages.com/packages/hk2-sanitize-search)
```

###  Alternatives

[mollie/magento2

Mollie Payment Module for Magento 2

1131.8M12](/packages/mollie-magento2)[run-as-root/magento2-prometheus-exporter

Magento2 Prometheus Exporter

68353.9k](/packages/run-as-root-magento2-prometheus-exporter)[myparcelnl/magento

A Magento 2 module that creates MyParcel labels

1859.0k](/packages/myparcelnl-magento)[mage-os/module-admin-activity-log

The Admin Activity extension makes it easy to track all admin activity with comprehensive audit logging.

293.3k](/packages/mage-os-module-admin-activity-log)[opengento/module-category-import-export

This module add the capability to import and export the categories from the back-office.

1310.2k1](/packages/opengento-module-category-import-export)[mage-os/module-llm-txt

AI-powered LLMs.txt generation for Magento 2 / Mage-OS stores. Help AI systems understand your store with OpenAI-generated content.

223.3k](/packages/mage-os-module-llm-txt)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
