PHP code example of 0mithun / php-zkteco

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

    

0mithun / php-zkteco example snippets


use Mithun\PhpZkteco\Libs\ZKTeco;

// Create instance with TCP protocol (recommended for stability)
$zk = new ZKTeco('192.168.1.100', 4370, protocol: 'tcp');

// Or use UDP protocol (default)
$zk = new ZKTeco('192.168.1.100', 4370, protocol: 'udp');

// Connect to device
if ($zk->connect()) {
    // Get all users
    $users = $zk->getUsers();
    
    // Get attendance logs
    $attendance = $zk->getAttendances();
    
    // Disconnect when done
    $zk->disconnect();
}

use Mithun\PhpZkteco\Libs\ZKTeco;

$zk = new ZKTeco(
    host: 'device-1.proxy.example.com',  // subdomain.base_domain
    port: 4370,  // ZKTeco device port (default)
    tcpmux: [
        'subdomain' => 'device-1',
        'port' => 1337,  // TCPMUX proxy port
    ]
);

if ($zk->connect()) {
    $users = $zk->getUsers();
    $zk->disconnect();
}

$zk = new ZKTeco(
    host: '192.168.1.100',     // Device IP/hostname (dPing: false,         // Ping before connecting (default: false)
    timeout: 25,               // Connection timeout in seconds (default: 25)
    password: 0,               // Device password/CMD key (default: 0)
    protocol: 'tcp',           // Protocol: 'tcp' or 'udp' (default: 'udp')
    tcpmux: []                 // TCPMUX config (optional, see below)
);

// TCPMUX configuration array:
$tcpmux = [
    'subdomain' => 'device-1', // Device subdomain for routing
    'port' => 1337,            // FRP TCPMUX port
];

$connected = $zk->connect();
if ($connected) {
    echo "Connected successfully!";
}

$zk->disconnect();

if ($zk->ping()) {
    echo "Device is reachable";
}

echo $zk->vendorName(); // "ZKTeco Inc."

echo $zk->deviceName(); // "K40"

echo $zk->deviceId(); // "1"

echo $zk->serialNumber(); // "PAS4234400018"

echo $zk->version(); // "Ver 6.60 Apr 13 2022"

echo $zk->osVersion(); // "1"

echo $zk->platform(); // "ZLM60_TFT"

echo $zk->fmVersion(); // "10"

echo $zk->pinWidth(); // "14"

echo $zk->workCode(); // "0"

echo $zk->ssr(); // "1"

echo $zk->faceFunctionOn(); // "0" or "1"

$memory = $zk->getMemoryInfo();
// Returns: {adminCounts, userCounts, userCapacity, logCounts, logCapacity}

echo $zk->getTime(); // "2026-02-17 12:30:00"

$zk->setTime('2026-02-17 12:00:00');

// Get all users
$users = $zk->getUsers();

// Each user contains:
// [
//     'uid' => 1,
//     'user_id' => '12345',
//     'name' => 'John Doe',
//     'role' => 0,
//     'password' => '1234',
//     'card_no' => '0000012345',
//     'device_ip' => '192.168.1.100'
// ]

// With filter callback
$admins = $zk->getUsers(function($user) {
    return $user['role'] == 14 ? $user : null;
});

// Add a regular user
$zk->setUser(1, '10001', 'John Doe', '1234', 0, 0);

// Add an admin user
$zk->setUser(2, '10002', 'Admin User', '5678', 14, 0);

$zk->removeUser(1);

// Delete all users with role 0
$zk->deleteUsers(function($user) {
    return $user['role'] == 0;
});

$zk->clearAllUsers();

$zk->clearAdminPriv();

// Get all attendance records
$logs = $zk->getAttendances();

// Each record contains:
// [
//     'uid' => 1,
//     'user_id' => 12345,
//     'state' => 1,
//     'record_time' => '2026-02-17 09:00:00',
//     'type' => 0,
//     'device_ip' => '192.168.1.100'
// ]

// With filter callback (e.g., today's records only)
$todayLogs = $zk->getAttendances(function($record) {
    if (str_starts_with($record['record_time'], date('Y-m-d'))) {
        return $record;
    }
    return null;
});

$zk->clearAttendance();

// Listen for real-time attendance events
$zk->getRealTimeLogs(function($log) {
    echo "User {$log['user_id']} punched at {$log['record_time']}\n";
    
    // $log contains:
    // [
    //     'user_id' => '12345',
    //     'record_time' => '2026-02-17 09:00:00',
    //     'state' => 1,
    //     'device_ip' => '192.168.1.100'
    // ]
}, timeout: 60); // Listen for 60 seconds

// Or listen indefinitely (Ctrl+C to stop)
$zk->getRealTimeLogs(function($log) {
    // Process attendance in real-time
    saveToDatabase($log);
});

use Mithun\PhpZkteco\Libs\Services\Util;

// Listen for attendance AND user enrollment events
$events = Util::EF_ATTLOG | Util::EF_ENROLLUSER | Util::EF_ENROLLFINGER;

$zk->getRealTimeEvents(function($event) {
    echo "Event: {$event['event_name']}\n";
    
    switch ($event['event_type']) {
        case Util::EF_ATTLOG:
            echo "Attendance: User {$event['user_id']} at {$event['record_time']}\n";
            break;
            
        case Util::EF_ENROLLUSER:
            echo "New user enrolled: {$event['user_id']}\n";
            break;
            
        case Util::EF_ENROLLFINGER:
            echo "Fingerprint enrolled for user {$event['user_id']}, finger {$event['finger_index']}\n";
            break;
            
        case Util::EF_UNLOCK:
            echo "Door {$event['door_id']} unlocked\n";
            break;
            
        case Util::EF_ALARM:
            echo "Alarm triggered: type {$event['alarm_type']}\n";
            break;
    }
}, $events, timeout: 3600); // Listen for 1 hour

[
    'event_type' => 1,              // Event constant (EF_ATTLOG, etc.)
    'event_name' => 'attendance',   // Human-readable name
    'device_ip' => '192.168.1.100',
    'timestamp' => '2026-02-17 09:00:00',
]

$fingerprints = $zk->getFingerprint(1);
// Returns array of fingerprint templates indexed by finger ID (0-9)

$zk->setFingerprint(1, $fingerprintData);

// Remove fingerprints 0 and 1 from user with UID 1
$deleted = $zk->removeFingerprint(1, [0, 1]);
echo "Deleted $deleted fingerprints";

$zk->disableDevice();
// Device screen shows "Working..." and ignores user input

$zk->enableDevice();

$zk->shutdown();

$zk->restart();

$zk->sleep();

$zk->resume();

$zk->writeLCD('Hello World!');

$zk->clearLCD();

$zk->testVoice(0);  // Play voice prompt index 0

// Common voice indices:
// 0 - "Thank you"
// 1 - "Incorrect fingerprint"
// 4 - "Thank you"

echo $zk->getDeviceData('TCPPort');     // "4370"
echo $zk->getDeviceData('DeviceID');    // "1"

$zk->setCustomData('my_company', 'Acme Corp');

echo $zk->getCustomData('my_company'); // "Acme Corp"

$zk->setPushCommKey('my_secret_key');

echo $zk->getPushCommKey();

try {
    $zk = new ZKTeco('192.168.1.100', 4370, protocol: 'tcp');
    
    if (!$zk->connect()) {
        throw new Exception('Failed to connect to device');
    }
    
    $users = $zk->getUsers();
    
    $zk->disconnect();
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

use Mithun\PhpZkteco\Libs\ZKTeco;

class AttendanceController extends Controller
{
    public function sync()
    {
        $zk = new ZKTeco(
            config('zkteco.ip'),
            config('zkteco.port'),
            protocol: config('zkteco.protocol', 'tcp')
        );
        
        if ($zk->connect()) {
            $attendances = $zk->getAttendances();
            
            foreach ($attendances as $record) {
                // Save to database
                Attendance::updateOrCreate(
                    ['uid' => $record['uid'], 'record_time' => $record['record_time']],
                    $record
                );
            }
            
            $zk->disconnect();
        }
        
        return response()->json(['synced' => count($attendances)]);
    }
}

define('ZKTECO_DEBUG', true);
define('ZKTECO_DEBUG_LOG', '/path/to/debug.log');

$zk = new ZKTeco('192.168.1.100', 4370, protocol: 'tcp');
bash
composer