PHPackages                             initphp/auth - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. initphp/auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

initphp/auth
============

PHP authentication &amp; authorization library with pluggable storage adapters (session, cookie, custom) and a small permission manager.

2.0.0(1mo ago)039MITPHPPHP ^8.0CI passing

Since Jul 14Pushed 3w ago1 watchersCompare

[ Source](https://github.com/InitPHP/Auth)[ Packagist](https://packagist.org/packages/initphp/auth)[ RSS](/packages/initphp-auth/feed)WikiDiscussions main Synced today

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

InitPHP Auth
============

[](#initphp-auth)

A small PHP authentication &amp; authorization library with pluggable storage adapters (session, signed cookie, or custom) and a tiny case-insensitive permission set.

[![Latest Stable Version](https://camo.githubusercontent.com/acb9a117ffb4a69d7139590d5fa2f4887512a88f326ee79ca8bc380fe0c7714e/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f617574682f76)](https://packagist.org/packages/initphp/auth)[![Total Downloads](https://camo.githubusercontent.com/112a623231bfbb9c0f907450b0546eabf335de716f3a5f69a92f596dca82b24d/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f617574682f646f776e6c6f616473)](https://packagist.org/packages/initphp/auth)[![CI](https://github.com/InitPHP/Auth/actions/workflows/ci.yml/badge.svg)](https://github.com/InitPHP/Auth/actions/workflows/ci.yml)[![License](https://camo.githubusercontent.com/42e531f2a656f82229678c9b1910b60b21998da27a5595401338468ef6fd3519/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f617574682f6c6963656e7365)](https://packagist.org/packages/initphp/auth)[![PHP Version Require](https://camo.githubusercontent.com/b96e3b25cb9fdd7b9b9cd5a05f219b5b1f7a4d7b12fcba93ca998415ecb92ecf/68747470733a2f2f706f7365722e707567782e6f72672f696e69747068702f617574682f726571756972652f706870)](https://packagist.org/packages/initphp/auth)

---

Features
--------

[](#features)

- **Pluggable storage** — pick `SessionAdapter`, `CookieAdapter`, or roll your own by implementing `AdapterInterface`.
- **Signed cookies** — JSON payload sealed with constant-time HMAC-SHA256; tampered values are dropped before decoding ever runs.
- **Strict cookie defaults** — `Secure`, `SameSite=Lax`, `HttpOnly`, and refusal of the unsafe `SameSite=None + Secure=false` combination.
- **Testable** — inject a `CookieWriterInterface` to capture every `setcookie()` call in unit tests instead of touching response headers.
- **Tiny permission set** — `Permission` does case-insensitive membership checks and ships magic accessors (`$perm->is_admin`).
- **Honest contracts** — typed properties, return types, `@throws` on every implementation-defined exception, PHPStan level 8 clean.

Requirements
------------

[](#requirements)

- PHP 8.0 or later (tested on 8.0 – 8.4)
- ext-json, ext-hash (both bundled with default PHP builds)
- [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) `^2.0`

Installation
------------

[](#installation)

```
composer require initphp/auth
```

Quick start
-----------

[](#quick-start)

### Session-backed auth

[](#session-backed-auth)

```
use InitPHP\Auth\Segment;

session_start();

$auth = Segment::session('auth');
$auth->set('user_id', 42)->set('role', 'editor');

if ($auth->has('user_id')) {
    $user = loadUser($auth->get('user_id'));
}

$auth->destroy(); // unsets $_SESSION['auth']
```

### Signed-cookie auth

[](#signed-cookie-auth)

```
use InitPHP\Auth\Segment;

$auth = Segment::cookie('auth', [
    // 32+ byte secret. Generate with bin2hex(random_bytes(32)) and
    // load it from configuration — never hard-code it in source.
    'salt'   => $_ENV['AUTH_COOKIE_SECRET'],
    'path'   => '/',
    'domain' => 'example.com',
]);

$auth->set('user_id', 42);
echo $auth->get('user_id'); // 42

$auth->destroy(); // emits a deletion cookie with matching path/domain
```

### Permissions

[](#permissions)

```
use InitPHP\Auth\Permission;

// Comparison is case-insensitive: 'Editor', 'EDITOR', and 'editor'
// are the same permission. The constructor normalizes its input the
// same way push() and remove() do.
$perm = new Permission(['Editor', 'post_list', 'post_edit']);

if ($perm->is('editor')) {
    $perm->push('user');         // returns 1
    $perm->remove('post_edit');  // returns 1
}

$perm->is('admin', 'editor');    // true if any of the names is present
isset($perm->is_admin);          // magic accessor for templates
```

Public API
----------

[](#public-api)

### `Segment`

[](#segment)

MethodPurpose`Segment::session(string $name, array $options = []): self`Build a segment backed by `$_SESSION`.`Segment::cookie(string $name, array $options): self`Build a segment backed by a signed cookie (`salt` required).`Segment::custom(string $name, class-string $adapterClass, array $options = []): self`Build a segment backed by your own adapter.`Segment::create(string $name, int|string $adapter, array $options = []): self`Legacy v1 factory; kept for BC.`adapter(): AdapterInterface`Escape hatch for adapter-specific methods.`get/set/has/remove/collective/destroy`Forwarded to the underlying adapter.### `AdapterInterface`

[](#adapterinterface)

MethodPurpose`get(string $key, mixed $default = null): mixed`Look up a value or fall back to `$default`.`set(string $key, mixed $value): static`Assign / replace a value.`collective(array $data): static`Atomic bulk write. Cookie adapters emit one `Set-Cookie` instead of N.`has(string $key): bool`Existence check (a stored `null` still counts as present).`remove(string ...$keys): static`Drop one or more keys (missing keys are a no-op).`destroy(): bool`Tear down the backing store. Subsequent calls raise `RuntimeException`.### `Permission`

[](#permission)

MethodPurpose`is(string ...$names): bool`True when **any** of the names is present. Case-insensitive.`push(string ...$names): int`Adds names, returns the count actually inserted.`remove(string ...$names): int`Removes names, returns the count actually removed; the list is reindexed.`getPermissions(): list`Snapshot of the current permission list.Magic accessors: `$perm->is_admin` (call), `isset($perm->is_admin)`, `unset($perm->is_admin)`.

CookieAdapter options
---------------------

[](#cookieadapter-options)

KeyTypeDefaultNotes`salt``string`— requiredAt least 32 bytes. Use `bin2hex(random_bytes(32))`.`expires``int|null`now + 86 400 sUnix timestamp. `null` resets to the default.`path``string``'/'`RFC 6265 path scope.`domain``string``''`Empty disables the `Domain` attribute.`secure``bool``true`When false, modern browsers reject `SameSite=None`.`httponly``bool``true`Blocks JS access via `document.cookie`.`samesite``'Lax'|'Strict'|'None'``'Lax'``'None'` is rejected unless `secure=true`.### Cookie wire format

[](#cookie-wire-format)

```
base64url(json_encode($data)) . "." . hash_hmac('sha256', $json, $salt)

```

The signature is verified with `hash_equals()` **before** the JSON is decoded, so a forged or modified cookie never reaches the parser.

Exceptions
----------

[](#exceptions)

ExceptionRaised when`InvalidArgumentException`Missing/short/non-string `salt`, `SameSite=None` without `Secure`, unknown adapter constant, missing adapter class, class that does not extend `AbstractAdapter`.`RuntimeException``SessionAdapter` constructed with no active session, or any read/write on an adapter whose `destroy()` has been called.`BadMethodCallException``Permission::__call()` invoked with a name that does not start with `is_`.Development
-----------

[](#development)

```
composer install
composer test         # PHPUnit
composer analyse      # PHPStan (level 8)
composer cs:check     # PHP-CS-Fixer dry-run
composer cs:fix       # PHP-CS-Fixer apply
```

CI runs the matrix across PHP 8.0, 8.1, 8.2, 8.3, and 8.4.

Documentation
-------------

[](#documentation)

- [docs/getting-started.md](docs/getting-started.md) — five-minute tour
- [docs/permissions.md](docs/permissions.md) — `Permission` recipes
- [docs/adapters/session.md](docs/adapters/session.md) — `SessionAdapter`
- [docs/adapters/cookie.md](docs/adapters/cookie.md) — `CookieAdapter`, salt generation, SameSite/Secure guidance
- [docs/adapters/custom.md](docs/adapters/custom.md) — building your own adapter (with a safe PDO-backed example)
- [docs/adapters/null.md](docs/adapters/null.md) — `NullAdapter` and when to use it
- [docs/upgrading-from-v1.md](docs/upgrading-from-v1.md) — v1 → v2 migration notes

Upgrading from v1
-----------------

[](#upgrading-from-v1)

v2 ships intentional behaviour changes — most notably a new cookie format (old cookies become unreadable and are rolled), case-folding moved into the `Permission` constructor, a stricter cookie default profile, `NullAdapter::has()` returning `false` instead of `true`, and a clean adapter interface that no longer enforces a constructor signature. See [docs/upgrading-from-v1.md](docs/upgrading-from-v1.md).

Contributing &amp; Security
---------------------------

[](#contributing--security)

- [Contributing guidelines](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md)
- [Code of Conduct](https://github.com/InitPHP/.github/blob/main/CODE_OF_CONDUCT.md)
- [Security policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md)

Credits
-------

[](#credits)

- [Muhammet ŞAFAK](https://www.muhammetsafak.com.tr) &lt;&gt;

License
-------

[](#license)

Released under the [MIT License](./LICENSE).

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance94

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~470 days

Total

4

Last Release

40d ago

Major Versions

1.x-dev → 2.x-dev2026-05-24

PHP version history (2 changes)1.0PHP &gt;=7.4

2.x-devPHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/4b6b34f3ac8938d8ee52ba3bd260680855dc5715c7b2929d9380de30d15a67dd?d=identicon)[muhammetsafak](/maintainers/muhammetsafak)

---

Top Contributors

[![muhammetsafak](https://avatars.githubusercontent.com/u/104234499?v=4)](https://github.com/muhammetsafak "muhammetsafak (5 commits)")

---

Tags

authenticationauthorizationcomposer-packagecookiehmacinitphppermissionsphpphp-libraryphp8securitysessionsigned-cookiesauthAuthenticationauthorizationpermissionssessioncookieinitphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/initphp-auth/health.svg)

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

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.7k147.0M288](/packages/league-oauth2-server)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

41021.9M91](/packages/auth0-auth0-php)[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2795.3M3](/packages/auth0-login)[dereuromark/cakephp-tinyauth

A CakePHP plugin to handle user authentication and authorization the easy way.

131240.2k13](/packages/dereuromark-cakephp-tinyauth)

PHPackages © 2026

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