PHPackages                             marcocesarato/security - 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. [Database &amp; ORM](/categories/database)
4. /
5. marcocesarato/security

ActiveConsole[Database &amp; ORM](/categories/database)

marcocesarato/security
======================

AIO Security Class offer an automatic system of protection for developers's projects and simplify some security operations as the check of CSRF or XSS all in a simple class. Infact you could just call the main method to have better security yet without too much complicated operations.

0.2.8.179(6y ago)392.9k↓50%13[4 issues](https://github.com/marcocesarato/PHP-AIO-Security-Class/issues)[2 PRs](https://github.com/marcocesarato/PHP-AIO-Security-Class/pulls)GPL-3.0-or-laterPHPPHP &gt;=5.1.2

Since Sep 11Pushed 1y ago7 watchersCompare

[ Source](https://github.com/marcocesarato/PHP-AIO-Security-Class)[ Packagist](https://packagist.org/packages/marcocesarato/security)[ RSS](/packages/marcocesarato-security/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)DependenciesVersions (4)Used By (0)

PHP AIO Security Class
======================

[](#php-aio-security-class)

**Version:** 0.2.8.183 beta

**Github:**

**Author:** Marco Cesarato

*IF YOU USE ON YOUR PROJECT SOME OF THESE METHODS PLEASE TO CREDIT ME :) THANK YOU!*

Description
-----------

[](#description)

This is a security class in php with some useful and automatic static methods.

The objective of this class is offer an automatic system of protection for developer's projects and simplify some security operations as the check of CSRF or XSS all in a simple class. In fact you could just call the main method to have better security yet without too much complicated operations.

### Antimalware Scanner

[](#antimalware-scanner)

Link Repository:

### Instructions

[](#instructions)

#### Composer

[](#composer)

1. Install composer
2. Type `composer require marcocesarato/security`
3. Go on `vendor/marcocesarato/security/` for have source
4. Move `.htaccess` on your ROOT directory (or try to merge it with your `.htaccess`)
5. Config the class
6. Enjoy

#### Implementation

[](#implementation)

1.1 - Include the class

```
use marcocesarato\security\Security;
```

or

```
include 'Security.php';
```

1.2 - Session store on database (Optional) (PDO/CPDO instances only)

```
$conn = new PDO(...);
Security::setDatabase($conn); // Or Security::$database = $conn;
```

2.0 - Just create a new object to be more at safe (the **constructor/putInSafety** filter $\_REQUEST and $\_GET globals, add some useful headers for security, check if there is an **Hijacking** and check the URL Request)

```
$isAPI = false; // default is FALSE (this remove some check that could block API request)
$security = new Security($isAPI);
```

or just call

```
$isAPI = false; // default is FALSE
Security::putInSafety($isAPI);
```

**NOTES:**

*1 You can also call only the methods that you need instead this method*

*2 Constructor and putInSafety are the **same** thing*

*3 These methods call **session\_start** then **don't** use it before/after*

*4 global **$\_POST** is not filtered. If you dont enable the cleanGlobals feature on settings*

All the uncleaned data can be recovered calling the following globals:

```
$GLOBALS['UNSAFE_SERVER'] = $_SERVER;
$GLOBALS['UNSAFE_COOKIE'] = $_COOKIE;
$GLOBALS['UNSAFE_GET'] = $_GET;
$GLOBALS['UNSAFE_POST'] = $_POST;
$GLOBALS['UNSAFE_REQUEST'] = $_REQUEST;
```

3 - Prevent **XSS/SQL Injection** on your variables with:

```
$is_html = true;        // default is TRUE
$have_quotes = true;    // default is TRUE
$escape_string = true;  // default is TRUE except if you set FALSE in class config
$var = Security::clean($_POST['var'], $is_html, $have_quotes, $escape_string);
echo $var;
```

or

```
Security::cleanGlobals();
```

**PS:** THIS COULD COMPROMISE DATA IF YOU SEND HTML WITH SCRIPT TAGS

*send with htmlentities could be a solution if you want inline js and clean globals at the same time*

4 - Use **output** method to filter your output (it also check for **CSRF**)

```
ob_start()

// ... Your code ...

echo Security::output(ob_get_clean());
```

Enjoy!

Options
-------

[](#options)

These are the options availables:

**PS:** *You can change the configuration as following for each parameters or simply editing the var directly on the class file:*

```
Security::$session_name = "MYSESSID";
```

### Configs

[](#configs)

OptionDescriptionDefault$basedirProject basedir where is located .htaccess\_\_DIR\_\_$saltSalt for crypt"\_SALT"$session\_nameSession cookie name"XSESSID"$session\_lifetimeSession lifetime"288000" (8 hours)$session\_regenerate\_idRegenerate session idFALSE$session\_databaseStore sessions on databaseFALSE$csrf\_sessionCSRF session token name"\_CSRFTOKEN"$csrf\_formtokenCSRF form token input name"\_FORMTOKEN"$headers\_cacheEnable header cacheTRUE$cookies\_encryptedEncrypt cookies \[PHP 5.3+\]FALSE$cookies\_enc\_prefixCookies encrypted prefix"SEC\_"$headers\_cache\_daysCache on NO HTML response (set 0 to disable)30$escape\_stringIf you use PDO I recommend to set this to falseTRUE$clean\_post\_xssRemove XSS on post globalTRUE$compress\_outputCompress outputTRUE$force\_httpsForce HTTPS (recommended if you have https)FALSE$hide\_errorsHide php errors (useful for hide vulnerabilities)TRUE$databasePDO instance for store sessions if enabled beforenull### Autostart

[](#autostart)

OptionDescriptionDefault$auto\_session\_managerRun session at startTRUE$auto\_cookies\_decryptAuto encrypt cookies \[PHP 5.3+\]FALSE$auto\_block\_torIf you want block TOR clientsTRUE$auto\_csrfIf you want enable CSRF (need use ::output method)FALSE$auto\_clean\_globalGlobal clean at startFALSE$auto\_antidosBlock the client ip when there are too many requestsTRUE### Error template

[](#error-template)

```
// Error Template
$error_callback = null; // Set a callback on errors
$error_template = '${ERROR_TITLE}${ERROR_BODY}';
```

Methods available:
------------------

[](#methods-available)

### Generic Methods

[](#generic-methods)

MethodParamsReturnDescriptionsetDatabase$connVoidSet PDO datbase instance for store sessions (only if enabled)\_\_construct / putInSafety$isAPI = falseVoidCall some methods:

headers `$isAPI`
secureSession `$isAPI`
secureFormRequest `$isAPI`
secureBots
secureRequest
secureBlockTor
secureHijacking
secureCookiessecureCSRF-VoidCheck for CSRFsecureCSRFCompare$key = '', $input\_name = nullBoolCompare CSRF TokensecureCSRFGenerate$key = ''StringGenerate CSRF TokensecureCSRFToken$key = ''StringGet CSRF TokensecureRequest-VoidEnable the WAF (Firewall) then check the request method and the URL to prevent some XSS/SQL Injections and bad requestssecureFormRequest$isAPI = falseVoidCheck if the form origin come from the same websitesecureSession-VoidSet custom session name for prevent fast identification of php and add some secure param to session cookie. PS: This method call `session_start`headers$isAPI = falseVoidSet some secure headers (to prevent some XSS, Clickjacking and others bad requests) and secure php settingheadersCache$cache\_days = nullVoidSet cache headerssecureCookies-VoidSet some secure parameter on cookies (autoencryption soon...)secureDOS-VoidBlock clients that do too much requests (after 10 requests within 1.5 seconds consecutive detect a DOS attempt, the first 4 times the client must wait 10 seconds after that its IP will be banned from the server)secureBlockBots-VoidBlock some generic bad bots/crawler/spiderssecureBlockTor-VoidBlock TOR clientssecureHijacking-VoidPrevent Hijacking and delete session### Utility Methods

[](#utility-methods)

MethodParamsReturnDescriptionencrypt$string, $key = nullStringEncrypt stringsdecrypt$string, $key = nullStringDecrypt stringsgenerateGUID-StringGenerate a GUIDgeneratePassword$length = 8, $available\_sets = 'luns'

(l = lowercase, u = uppercase, n = numbers, s = special chars)StringGenerate a completly random and strong passwordgenerateFriendlyPassword$string, $strong\_lv = 1StringGenerate a user friendly random password. Strong level go from 0 to 2.

EXAMPLE:
Marco Cesarato 1996
Ce$Ar4t0\_m4RCo\_1996passwordHash$password, $cost = 10 (4-30)StringHash the passwordspasswordVerify$password, $hashBooleanVerify if password hash (returned by passwordHash) matchpasswordStrength$passwordIntegerReturn password strength score from 0 to 10 (under 6 is a bad score)getCookie$nameStringGet decrypted cookiesetCookie$name, $value, $expires = 2592000, $path = "/", $domain = null, $secure = false, $httponly = trueBooleanSet encrypted cookiecheckHTTPS-BooleanCheck if site is running over httpsunsetCookie$nameStringUnset a cookieclientIP-StringGet real client IP addressclientIPs-ArrayGet all client IP addressesclientIsTor-BooleanCheck if client use TORsecureJSONP$json, $callbackStringPrevent malicious callbacks from being used in JSONP requests.secureDownload$filename, $name = nullVoidSecure headers for download requestisInfectedFavicon$fileBooleanReturn if is an infected favicon fileisInfectedFile$fileBooleanReturn if is an infected php filesecureUpload$file, $destinationBooleanFile upload with scanenvironmentCheck-ArrayCheck environment configuration and return the current and the recommended php.ini configuration### Cleaning Methods

[](#cleaning-methods)

MethodParamsReturnDescriptionclean$data, $html = true, $quotes = true, $xss = trueMixedClean value form XSS, SQL Injection etc… recursivelycleanGlobals-VoidClean all input global vars ($\_*REQUEST,$\_POST,*$\_*GET,*$\_COOKIE)
THIS COULD COMPROMISE SOME DATArestoreGlobals-VoidRestore globals to uncleaned/unsafe globalsdebugGlobals-ArrayReturn an array with the safe, unsafe and the current globals, this is userful for comparingescapeXSS$dataMixedClean value from XSS recursivelyescapeSQL$dataMixedClean from SQL Injection (similar at mysql\_real\_escape) recursivelyescapeAttr$dataMixedEscape for HTML attribute values
`` recursivelystripTags$dataMixedStrip tags recursivelystripTagsContent$data, $tags = '', $invert = falseMixedStrip tags and contents recursivelytrim$dataMixedTrim recursivelystripslashes$dataMixedStrip slashes recursively### Output Methods

[](#output-methods)

MethodParamsReturnDescriptionoutput$buffer, $type = (html|css|js|json|xml|csv|txt), $cache\_days = null, $compress = trueStringPut in safety HTML if is HTML, compress HTML if is HTML, check for CSRF and add cache headers if isn't HTML (usually used with ob\_start)secureHTML$bufferStringPut in safety some html elements, block old browsers console scripts executions on output buffer and add automatically the CSRF tokencaptcha$base64 = falseVoidPrint captcha image and die or if base64 return the image in base64.captchaVerify$input\_name = 'captcha'VoidValidate captchacaptchaPrint$class = '', $input\_name = 'captcha'StringReturn the captcha input field and the image in htmlcaptchaCode-StringGet captcha codecompressOutput$bufferStringCompression genericcompressHTML$htmlStringCompression of HTMLcompressJS$jsStringCompression of JScompressCSS$cssStringCompression of CSSerror$code = 404, $message = "Not found!", $title = 'Error'VoidError
(use $error\_template and $error\_callback)Screenshots
-----------

[](#screenshots)

[![XSSBlock](screenshots/xssblock_screen.png)](screenshots/xssblock_screen.png)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.3% 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

2441d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/36447518?v=4)[Marco Cesarato](/maintainers/marcocesarato)[@marcocesarato](https://github.com/marcocesarato)

---

Top Contributors

[![marcocesarato](https://avatars.githubusercontent.com/u/36447518?v=4)](https://github.com/marcocesarato "marcocesarato (48 commits)")[![renovate[bot]](https://avatars.githubusercontent.com/in/2740?v=4)](https://github.com/renovate[bot] "renovate[bot] (3 commits)")[![ImgBotApp](https://avatars.githubusercontent.com/u/31427850?v=4)](https://github.com/ImgBotApp "ImgBotApp (1 commits)")

---

Tags

autocompleteclasscleaningclickjackingcompresscookiescryptcsrfescapefirewallhijackinghtaccessinjectionphpsafetyscannersecuritysqlwafxss

### Embed Badge

![Health badge](/badges/marcocesarato-security/health.svg)

```
[![Health](https://phpackages.com/badges/marcocesarato-security/health.svg)](https://phpackages.com/packages/marcocesarato-security)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90440.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)[wildside/userstamps

Laravel Userstamps provides an Eloquent trait which automatically maintains `created\_by` and `updated\_by` columns on your model, populated by the currently authenticated user in your application.

7511.7M13](/packages/wildside-userstamps)

PHPackages © 2026

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