PHPackages                             yetiforce/csrf-magic - 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. [Security](/categories/security)
4. /
5. yetiforce/csrf-magic

ActiveLibrary[Security](/categories/security)

yetiforce/csrf-magic
====================

Cross Site Request Forgery security library

v1.1.7(2y ago)3161.2k↑180.8%82BSD-2-ClausePHPPHP &gt;=7.1.0

Since Mar 21Pushed 2y ago4 watchersCompare

[ Source](https://github.com/YetiForceCompany/csrf-magic)[ Packagist](https://packagist.org/packages/yetiforce/csrf-magic)[ Docs](https://github.com/YetiForceCompany/csrf-magic)[ RSS](/packages/yetiforce-csrf-magic/feed)WikiDiscussions master Synced today

READMEChangelog (10)DependenciesVersions (14)Used By (2)

[![Latest Stable Version](https://camo.githubusercontent.com/faa749509c302836ed9c7d036dc5b1b2648bd359d4c84d91321b5b3594f02280/68747470733a2f2f706f7365722e707567782e6f72672f79657469666f7263652f637372662d6d616769632f762f737461626c65)](https://packagist.org/packages/yetiforce/csrf-magic)[![release date](https://camo.githubusercontent.com/cf17ddf2d40e9e00ef0a232ff93778cc83e3ee5a1039f2348cf3ec9ed423a926/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652d646174652f59657469466f726365436f6d70616e792f637372662d6d61676963)](https://camo.githubusercontent.com/cf17ddf2d40e9e00ef0a232ff93778cc83e3ee5a1039f2348cf3ec9ed423a926/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652d646174652f59657469466f726365436f6d70616e792f637372662d6d61676963)[![PHP Version](https://camo.githubusercontent.com/345366c6fb8d7a83552a33801bafd47f12d9e43b85e558bc4b4d72842a83e342/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f79657469666f7263652f637372662d6d61676963)](https://camo.githubusercontent.com/345366c6fb8d7a83552a33801bafd47f12d9e43b85e558bc4b4d72842a83e342/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f79657469666f7263652f637372662d6d61676963)

Add the following line to the top of all web-accessible PHP pages. If you have a common file included by everything, put it there.

```
include_once '/path/to/csrf-magic.php';

```

Do it, test it, then forget about it. csrf-magic is protecting you if nothing bad happens. Read on if you run into problems.

```
                         TABLE OF CONTENTS
                      + ------------------- +
                        1. TIPS AND TRICKS
                        2. AJAX
                        3. CONFIGURE
                        4. THANKS
                        5. FOOTNOTES
                      + ------------------- +

```

1. TIPS AND TRICKS

    - If your JavaScript and AJAX is persistently getting errors, check the AJAX section below on how to fix.
    - The CSS overlay protection makes it impossible to display your website in frame/iframe elements. You can disable it with csrf\_conf('frame-breaker', false) in your csrf\_startup() function.
    - csrf-magic will start a session. To disable, use csrf\_conf('auto-session', false) in your csrf\_startup() function.
    - The default error message is a little user unfriendly. Write your own function which outputs an error message and set csrf\_conf('callback', 'myCallbackFunction') in your csrf\_startup() function.
    - Make sure csrf\_conf('secret', 'ABCDEFG') has something random in it. If the directory csrf-magic.php is in is writable, csrf-magic will generate a secret key for you in the csrf-secret.php file.
    - Remember you can use auto\_prepend to include csrf-magic.php on all your pages. You may want to create a stub file which you can include that includes csrf-magic.php as well as performs configuration.
    - The default expiration time for tokens is two hours. If you expect your users to need longer to fill out forms, be sure to enable double submission when the token is invalid.
2. AJAX

csrf-magic has the ability to dynamically rewrite AJAX requests which use XMLHttpRequest. However, due to the invasiveness of this procedure, it is not enabled by default. You can enable it by adding this code before you include csrf-magic.php.

```
function csrf_startup() {
    csrf_conf('rewrite-js', '/web/path/to/Csrf.js');
}
// include_once '/path/to/csrf-magic.php';

```

(Be sure to place Csrf.js somewhere web accessible).

The default method CSRF Magic uses to rewrite AJAX requests will only work for browsers with support for XmlHttpRequest.prototype (this excludes all versions of Internet Explorer). See this page for more information:

However, Csrf.js will automatically detect and play nice with the following JavaScript frameworks:

```
* jQuery
* Prototype
* MooTools
* Ext
* Dojo

```

(Note 2013-07-16: It has been a long time since this manual support has been updated, and some JavaScript libraries have placed their copies of XHR in local variables in closures, which makes it difficult for us to monkey-patch it in automatically.)

To rewrite your own JavaScript library to use Csrf.js, you should modify your function that generates XMLHttpRequest to have this at the end:

```
return new CsrfMagic(xhrObject);

```

With whatever xhrObject may be. If you have literal instances of XMLHttpRequest in your code, find and replace ''new XMLHttpRequest'' with ''new CsrfMagic'' (CsrfMagic will automatically instantiate an XMLHttpRequest object in a cross-platform manner as necessary).

If you don't want csrf-magic monkeying around with your XMLHttpRequest object, you can manually rewrite your AJAX code to include the variable. The important information is stored in the global variables csrfMagicName and csrfMagicToken. CsrfMagic.process may also be of interest, as it takes one parameter, a querystring, and prepends the CSRF token to the value.

3. CONFIGURE

csrf-magic has some configuration options that you can set inside the csrf\_startup() function. They are described in csrf-magic.php, and you can set them using the convenience function csrf\_conf($name, $value).

For example, this is a recommended configuration:

```
/**
 * This is a function that gets called if a csrf check fails. csrf-magic will
 * then exit afterwards.
 */
function my_csrf_callback() {
    echo "You're doing bad things young man!";
}

function csrf_startup() {

    // While csrf-magic has a handy little heuristic for determining whether
    // or not the content in the buffer is HTML or not, you should really
    // give it a nudge and turn rewriting *off* when the content is
    // not HTML. Implementation details will vary.
    if (isset($_POST['ajax'])) csrf_conf('rewrite', false);

    // This is a secret value that must be set in order to enable username
    // and IP based checks. Don't show this to anyone. A secret id will
    // automatically be generated for you if the directory csrf-magic.php
    // is placed in is writable.
    csrf_conf('secret', 'ABCDEFG123456');

    // This enables JavaScript rewriting and will ensure your AJAX calls
    // don't stop working.
    csrf_conf('rewrite-js', '/Csrf.js');

    // This makes csrf-magic call my_csrf_callback() before exiting when
    // there is a bad csrf token. This lets me customize the error page.
    csrf_conf('callback', 'my_csrf_callback');

    // While this is enabled by default to boost backwards compatibility,
    // for security purposes it should ideally be off. Some users can be
    // NATted or have dialup addresses which rotate frequently. Cookies
    // are much more reliable.
    csrf_conf('allow-ip', false);

}

// Finally, include the library
include_once '/path/to/csrf-magic.php';

```

Configuration gets stored in the $GLOBALS\['csrf'\] array.

4. THANKS

My thanks to Chris Shiflett, for unintentionally inspiring the idea, as well as telling me the original variant of the Bob and Mallory story, and the Django CSRF Middleware authors, who thought up of this before me. Gareth Heyes suggested using the frame-breaker option to protect against CSS overlay attacks.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 51.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

Every ~172 days

Recently: every ~37 days

Total

13

Last Release

960d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2b9962f8b85b97e5d98b46f22e9259d62bb72b6e3f1cc9b7464f0f57c2e6cf52?d=identicon)[yetiforce](/maintainers/yetiforce)

---

Top Contributors

[![mariuszkrzaczkowski](https://avatars.githubusercontent.com/u/10198654?v=4)](https://github.com/mariuszkrzaczkowski "mariuszkrzaczkowski (20 commits)")[![ezyang](https://avatars.githubusercontent.com/u/13564?v=4)](https://github.com/ezyang "ezyang (9 commits)")[![TomaszQr](https://avatars.githubusercontent.com/u/14273211?v=4)](https://github.com/TomaszQr "TomaszQr (5 commits)")[![NewEraCracker](https://avatars.githubusercontent.com/u/416945?v=4)](https://github.com/NewEraCracker "NewEraCracker (4 commits)")[![rskrzypczak](https://avatars.githubusercontent.com/u/10221999?v=4)](https://github.com/rskrzypczak "rskrzypczak (1 commits)")

---

Tags

phpsecuritycsrf

### Embed Badge

![Health badge](/badges/yetiforce-csrf-magic/health.svg)

```
[![Health](https://phpackages.com/badges/yetiforce-csrf-magic/health.svg)](https://phpackages.com/packages/yetiforce-csrf-magic)
```

###  Alternatives

[dneustadt/csrf-cookie-bundle

CSRF protection cookie for use with XHR

1380.7k1](/packages/dneustadt-csrf-cookie-bundle)

PHPackages © 2026

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