PHP code example of msaied / zkteco

1. Go to this page and download the library: Download msaied/zkteco 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/ */

    

msaied / zkteco example snippets


use ZkTeco\TCP\Device;

$device = new Device(host: '192.168.1.201');

// Managed scope: connects, disables the device for the duration, then
// re-enables and disconnects it even if the callback throws.
$users = $device->session(fn (Device $d) => $d->users()->all());

foreach ($users as $user) {
    echo "{$user->uid}\t{$user->userId}\t{$user->name}\n";
}

$device = new Device(
    host: '192.168.1.201',
    port: 4370,    // default ZK port
    commKey: 0,    // numeric comm password guarding the session (0 if unset)
    timeout: 5.0,  // socket timeout in seconds
    useUdp: false, // UDP is not implemented yet — see Limitations
    nameEncoding: 'UTF-8', // device name codepage — see "Non-ASCII names" below
);

$device = new Device(host: '192.168.1.201', nameEncoding: 'Windows-1256'); // Arabic

$device->session(function (Device $d) {
    $d->users()->save(new User(uid: 5, userId: '1005', name: 'Asma'));

    return $d->attendance()->all();
});

$device->connect();
try {
    // ... long-lived work ...
} finally {
    $device->disconnect();
}

use ZkTeco\Values\User;
use ZkTeco\Enums\Privilege;

$users = $device->users();

$users->all();                 // list<User>
$users->find(5);               // ?User by device-local uid
$users->save(new User(         // create or overwrite
    uid: 5,
    userId: '1005',            // human-facing employee number
    name: 'Asma',
    privilege: Privilege::User,
    password: null,
    cardNumber: null,
    groupId: 0,
));
$users->delete(5);             // delete by uid (also clears that user's templates)
$users->clear();               // wipe all users, fingerprints and attendance

$attendance = $device->attendance();

$records = $attendance->all(); // list<AttendanceRecord>
$attendance->clear();          // wipe the on-device attendance log

$templates = $device->templates();

$templates->all();                   // list<Template> — every template on the device
$templates->forUser(5);              // list<Template> for one user's uid
$templates->delete(5, 0);            // delete user 5's finger slot 0
$templates->upload($user, $fingers); // store a list<Template> for a user

$device->connect();
try {
    $captured = $device->templates()->enroll($user, fingerIndex: 6); // bool
} finally {
    $device->disconnect();
}

$device->templates()->enroll($user, fingerIndex: 6, trace: function (string $event, array $context) {
    logger()->debug("enroll: {$event}", $context);
});

$info = $device->info();

$info->firmwareVersion(); // e.g. "Ver 6.60 May 14 2018"
$info->serialNumber();    // device serial
$info->name();            // device name / model ('' if unset)
$info->time();            // DateTimeImmutable — the device clock
$info->setTime(new DateTimeImmutable('now'));

$control = $device->control();

$control->disable();   // put the device into maintenance mode
$control->enable();    // bring it back
$control->restart();
$control->powerOff();
$control->clearData(); // factory-style data wipe (users + templates + attendance)

$device->connect();
foreach ($device->realtime()->live() as $record) {
    if ($record === null) {
        continue; // idle heartbeat — no punch this interval
    }

    echo "{$record->userId} punched at {$record->recordedAt->format('H:i:s')}\n";
}

'adms' => [
    'enabled'         => (bool) env('ZKTECO_ADMS_ENABLED', false),
    'prefix'          => env('ZKTECO_ADMS_PREFIX', 'iclock'),
    'middleware'      => [],   // e.g. ['throttle:adms']
    'auto_register'   => (bool) env('ZKTECO_ADMS_AUTO_REGISTER', false),
    'allowed_serials' => array_values(array_filter(
        explode(',', (string) env('ZKTECO_ADMS_ALLOWED_SERIALS', '')),
    )),
],

use ZkTeco\ADMS\Registry\DeviceRegistry;

app(DeviceRegistry::class)->approve('ABC1234567890');

use ZkTeco\Laravel\Events\PunchReceived;
use ZkTeco\Laravel\Models\Attendance;

class StorePunch
{
    public function handle(PunchReceived $event): void
    {
        Attendance::create([
            'connection'  => $event->connection, // serial (ADMS) or connection name (socket)
            'uid'         => $event->record->uid,
            'user_id'     => $event->record->userId,
            'recorded_at' => $event->record->recordedAt,
            'verify_mode' => $event->record->verifyMode->name,
            'punch_state' => $event->record->punchState->name,
        ]);
    }
}

class ArchivePhoto
{
    public function handle(\ZkTeco\Laravel\Events\AttendancePhotoReceived $event): void
    {
        Storage::put(
            "punches/{$event->connection}/{$event->photo->userId}.jpg",
            $event->photo->image, // raw JPEG bytes
        );
    }
}

use ZkTeco\Laravel\Facades\ZkTeco;
use ZkTeco\Values\User;

ZkTeco::push('ABC1234567890')->reboot();
ZkTeco::push('ABC1234567890')->syncTime();                 // defaults to now
ZkTeco::push('ABC1234567890')->upsertUser(new User(
    uid: 0, userId: '1005', name: 'Asma',
));
ZkTeco::push('ABC1234567890')->deleteUser('1005');
ZkTeco::push('ABC1234567890')->clearLog();

use ZkTeco\Laravel\Events\CommandAcknowledged;

class TrackCommand
{
    public function handle(CommandAcknowledged $event): void
    {
        if ($event->result->succeeded()) {        // returnCode === 0
            logger()->info("ok: {$event->command->command}");
        } else {
            logger()->warning("device returned {$event->result->returnCode}");
        }
    }
}

return [
    'default' => env('ZKTECO_CONNECTION', 'default'),

    'connections' => [
        'default' => [
            'host'     => env('ZKTECO_HOST', '192.168.1.201'),
            'port'     => (int) env('ZKTECO_PORT', 4370),
            'comm_key' => (int) env('ZKTECO_COMM_KEY', 0),
            'timeout'  => (float) env('ZKTECO_TIMEOUT', 5),
            'udp'      => (bool) env('ZKTECO_UDP', false),
            'name_encoding' => env('ZKTECO_NAME_ENCODING', 'UTF-8'), // device codepage for names
        ],
    ],

    'adms' => [ /* see "Enabling the endpoints" above */ ],
];

use ZkTeco\Laravel\Facades\ZkTeco;

$users = ZkTeco::connection()->session(            // default connection
    fn ($device) => $device->users()->all()
);

$users = ZkTeco::connection('warehouse')->session( // a named connection
    fn ($device) => $device->users()->all()
);

use ZkTeco\Exceptions\ConnectionException;
use ZkTeco\Exceptions\ResponseException;

try {
    $device->session(fn ($d) => $d->users()->save($user));
} catch (ConnectionException $e) {
    // unreachable, wrong comm key, etc.
} catch (ResponseException $e) {
    // device refused the write
}

catch (ZkTeco\Exceptions\ZkException $e) {
    $e->errorCode->value; // 'connection_failed'  — switch on this, or use it as a key
    $e->context;          // ['host' => '192.168.1.201', 'port' => 4370, 'reason' => '...']
    $e->getMessage();     // English fallback, always populated
}

// lang/vendor/zkteco/fr/errors.php
return [
    'connection_failed' => 'Connexion impossible à l’appareil :host::port (:reason).',
    'timeout' => 'Délai dépassé en attendant une réponse de l’appareil.',
    // … one entry per ErrorCode value
];
bash
php artisan vendor:publish --tag=zkteco-config
bash
php artisan vendor:publish --tag=zkteco-migrations
php artisan migrate
bash
# Terminal 1 — a tiny PHP built-in-server listener wired to the real core
php -S 0.0.0.0:8080 examples/adms-listener.php

# Terminal 2 — approve a device that has dialed in
php examples/adms-approve.php <serial>
bash
php artisan zkteco:listen            # default connection
php artisan zkteco:listen warehouse  # a named connection
bash
php artisan vendor:publish --tag=zkteco-lang