PHP code example of rafaelgou / php-apache2-basic-auth

1. Go to this page and download the library: Download rafaelgou/php-apache2-basic-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rafaelgou / php-apache2-basic-auth example snippets




// ...
use Apache2BasicAuth\Service as HTService;

$htService = new HTService(
    'PATH_TO/.htpasswd',
    'PATH_TO/.htgroups'
);



// ... Instanciate the Service ...

// Create a new group
$group = $htService->createGroup();
$group->setName('admin')
    ->addUser('mateus')
    ->addUser('tiago');

// Groups can be also set:
$group->setUsers(array('bernardo', 'larissa'));

// Staging to write    
$htService->persist($group);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Create a new group
$group = $htService->findGroup('admin');
$group
    ->removeUser('mateus')
    ->addUser('ana');

// Staging to write    
$htService->persist($group);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Create a new group
$group = $htService->findGroup('admin');

// Staging to write    
$htService->htService->removeGroup($group);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Create a new user
$user = $htService->createUser();
$user->setUsername('rafael')
    ->setPassword('my_pass_123')
    ->setAddGroup('admin')
    ->setAddGroup('finance');

// Groups can be also set:
$user->setGroups(array('opperations', 'support'));

// Staging to write    
$htService->persist($user);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Finding an existing user
$user = $htService->findUser('rafael');
$user->setPassword('my_pass_123')
    ->removeGroup('admin')
    ->setAddGroup('marketing');

// Staging to write    
$htService->persist($user);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Finding an existing user
$user = $htService->findUser('rafael');

// Staging to write    
$htService->htService->removeUser($user);

// Writing to disc
$htService->write();



// ... Instanciate the Service ...

// Getting Users
$users = $htService->getUsers();

// The key is the username too
foreach ($users as $username => $user) {
    echo $user->getUsername();
    echo $user->getHash(); // Hashed password
    echo implode(', ', $user->getGroups());
}

// Getting Groups
$groups = $htService->getGroups();

// The key is the username too
foreach ($groups as $groupname => $group) {
    echo $group->getName();
    echo implode(', ', $user->getUsers());
}