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 Authorization Library

1.0(3y ago)035MITPHPPHP &gt;=7.4

Since Jul 14Pushed 3y ago1 watchersCompare

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

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

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

[](#initphp-auth)

This library makes logged in user data more organized and easily accessible.

Features
--------

[](#features)

- Easy to use user permissions manager.
- Ability to use user authorization data on cookies or sessions.
- Ability to write and use your own authorization class.

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

[](#requirements)

- PHP 7.4 or later
- [InitPHP ParameterBag Library](https://github.com/InitPHP/ParameterBag)

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

[](#installation)

```
composer require initphp/auth

```

Usage
-----

[](#usage)

### Use of Permissions

[](#use-of-permissions)

It is a small but capable library that you can use to define user permissions.

```
require_once 'vendor/autoload.php';

$perm = new \InitPHP\Auth\Permission([
    'editor',
    'post_list', 'post_edit', 'post_add', 'post_delete'
]);

if($perm->is('editor')){
    // has "editor" authority
    $perm->remove('editor'); // remove "editor" permissions
    $perm->push('user'); // added "user" permission
}
```

**Multiple use :**

```
/** @var \InitPHP\Auth\Permission $perm */

$perm->is('admin', 'editor'); // True if "admin" or "editor" privileges. Returns false if none of the specified are present.

$perm->remove('admin', 'editor'); // Removes the specified permissions. And returns the actual number of permissions removed.

$perm->push('admin', 'editor'); // Adds the specified permissions. Returns the number of permissions added.
```

### Cookie Adapter

[](#cookie-adapter)

It manages session data on `$_COOKIE` provided by PHP.

```
require_once 'vendor/autoload.php';
use InitPHP\Auth\Segment;

$auth = Segment::create('authorization', Segment::ADAPTER_COOKIE, [
    'salt'  => 'QO.@zeZiFgSvQd-:' // It is used to verify that the data in this cookie has not changed. Define a unique and secret string of at least 8 characters.
]);
```

### Session Adapter

[](#session-adapter)

It manages session data on `$_SESSION` provided by PHP.

```
session_start();
require_once 'vendor/autoload.php';
use InitPHP\Auth\Segment;

$auth = Segment::create('authorization', Segment::ADAPTER_SESSION);
```

### Write and use your own adapter.

[](#write-and-use-your-own-adapter)

In the example below you can see an example of a simple adapter for basic auth with the help of a database connection.

***Note :*** The example below is purely for instructional purposes. Using the code below directly will cause serious security vulnerabilities.

```
namespace App;

class BasicAuthAdapter extends InitPHP\Auth\AbstractAdapter
{
    /** @var \PDO */
    protected $pdo;

    protected array $userInfo = [];

    public function __construct(string $name, array $options = [])
    {
        $this->pdo = new \PDO($options['dsn'], $options['username'], $options['password']);
        $statement = $this->pdo->prepare("SELECT * FROM `ùsers` WHERE `user_name` = :user_name AND `password` = :password LIMIT 1");
        $statement->execute([
            ':user_name'    => ($_SERVER['PHP_AUTH_USER'] ?? ''),
            ':password'     => md5(($_SERVER['PHP_AUTH_PW'] ?? ''))
        ]);
        if($statement->rowCount() > 0){
            $this->userInfo = $statement->fetch(\PDO::FETCH_ASSOC);
        }else{
            header("WWW-Authenticate: Basic realm=\"Privare Area\"");
            header("HTTP/1.0 401 Unauthorized");
            echo "Sorry, you need proper credendtials";
            exit;
        }
    }

    public function get(string $key, $default = null)
    {
        return $this->userInfo[$key] ?? $default;
    }

    public function set(string $key, $value): self
    {
        if($key == 'user_name'){
            return $this;
        }
        $statement = $this->pdo->query("UPDATE `ùsers` SET `" . $key . "` = '" . (string)$value . "' WHERE `ùser_name` = " . $this->userInfo['user_name']);
        if($statement !== FALSE){
            unset($this->userInfo[$key]);
        }
        return $this;
    }

    public function collective(array $data): self
    {
        if(isset($data['user_name'])){
            unset($data['user_name']);
        }
        if(empty($data)){
            return $this;
        }
        $sql = "UPDATE `ùsers` SET";
        foreach ($data as $key => $value) {
            $sql .= " `" . $key . "` = '" . $value . "'";
        }
        $sql .= " WHERE `ùser_name` = '" . $this->userInfo['user_name'] . "'";
        if($this->pdo->query($sql) !== FALSE){
            $this->userInfo = array_merge($this->userInfo, $data);
        }
        return $this;
    }

    public function has(string $key): bool
    {
        return isset($this->userInfo[$key]);
    }

    public function remove(string ...$key): self
    {
        foreach ($key as $name) {
            if($key == 'user_name'){
                continue;
            }
            if(isset($this->userInfo[$key])){
                $this->userInfo[$key];
                $this->pdo->query("UPDATE `ùsers` SET `" . $key . "` = NULL WHERE `ùser_name` = '".$this->userInfo['user_name']."'");
            }
        }
        return $this;
    }

    public function destroy(): bool
    {
        $this->userInfo = [];
        return true;
    }

}
```

```
$segment = new \InitPHP\Auth\Segment('', \App\BasicAuthAdapter::class, [
    'dsn'       => 'mysql:host=localhost;dbname=test_database;charset=utf8mb4',
    'username'  => 'root',
    'password'  => ''
]);
```

Credits
-------

[](#credits)

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

License
-------

[](#license)

Copyright © 2022 [MIT License](./LICENSE)

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

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

Unknown

Total

1

Last Release

1403d ago

### 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 (2 commits)")

### 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

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

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