PHP code example of jmrashed / zkteco

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

    

jmrashed / zkteco example snippets


    
    if (function_exists('socket_create')) {
        echo "Sockets extension is enabled.";
    } else {
        echo "Sockets extension is not enabled.";
    }
    

use Jmrashed\Zkteco\Lib\ZKTeco;

$zk = new ZKTeco('192.168.1.201');

// Using IP address and port
$zk = new ZKTeco('192.168.1.201', 8080);

// Connect to the ZKTeco device
// Returns a boolean indicating whether the connection was successful
$connected = $zk->connect();

// Disconnect from the ZKTeco device
// Returns a boolean indicating whether the disconnection was successful
$disconnected = $zk->disconnect();

// Enable the ZKTeco device
// Returns a boolean or mixed value indicating whether the device was enabled
// Note: This method should be called after reading/writing any device information
$enabled = $zk->enableDevice();

// Disable the ZKTeco device
// Returns a boolean or mixed value indicating whether the device was disabled
// Note: This method should be called before reading or writing any device information
$disabled = $zk->disableDevice();

// Get the firmware version of the ZKTeco device
// Returns a boolean or mixed value containing the device version information
$version = $zk->version();

// Get the operating system version of the ZKTeco device
// Returns a boolean or mixed value containing the device OS version information
$osVersion = $zk->osVersion(); 

// Turn off the ZKTeco device
// Returns a boolean or mixed value indicating whether the device shutdown was successful
$shutdown = $zk->shutdown();

// Restart the ZKTeco device
// Returns a boolean or mixed value indicating whether the device restart was successful
$restart = $zk->restart();

// Put the ZKTeco device into sleep mode
// Returns a boolean or mixed value indicating whether the device entered sleep mode
$sleep = $zk->sleep();

// Resume the ZKTeco device from sleep mode
// Returns a boolean or mixed value indicating whether the device resumed from sleep mode
$resume = $zk->resume();

// Test the voice functionality of the ZKTeco device by saying "Thank you"
// Returns a boolean or mixed value indicating whether the voice test was successful
$voiceTest = $zk->testVoice();

// Get the platform information of the ZKTeco device
// Returns a boolean or mixed value containing the platform information
$platform = $zk->platform();

// Get the firmware version of the ZKTeco device
// Returns a boolean or mixed value containing the firmware version information
$fmVersion = $zk->fmVersion();

// Get the work code information of the ZKTeco device
// Returns a boolean or mixed value containing the work code information
$workCode = $zk->workCode(); 


// Get the name of the ZKTeco device
// Returns a boolean or mixed value containing the device name information
$deviceName = $zk->deviceName(); 


// Get the current time of the ZKTeco device
// Returns a boolean or mixed value containing the device time information
// Format: "Y-m-d H:i:s"
$deviceTime = $zk->getTime();


// Set the time of the ZKTeco device
// Parameters:
// - string $t: Time string in format "Y-m-d H:i:s"
// Returns a boolean or mixed value indicating whether the device time was successfully set
$setTimeResult = $zk->setTime($timeString);

// Get the list of users stored in the ZKTeco device
// Returns an array containing user information
$users = $zk->getUser();

// Set a user in the ZKTeco device
// Parameters:
// - int $uid: Unique ID (max 65535)
// - int|string $userid: ID in DB (max length = 9, only numbers - depends device setting)
// - string $name: User name (max length = 24)
// - int|string $password: Password (max length = 8, only numbers - depends device setting)
// - int $role: User role (default Util::LEVEL_USER)
// - int $cardno: Card number (default 0, max length = 10, only numbers)
// Returns a boolean or mixed value indicating whether the user was successfully set
$setUserResult = $zk->setUser($uid, $userid, $name, $password, $role, $cardno);

// Remove all admin users from the ZKTeco device
// Returns a boolean or mixed value indicating whether all admin users were successfully removed
$clearedAdmin = $zk->clearAdmin();

// Remove all users from the ZKTeco device
// Returns a boolean or mixed value indicating whether all users were successfully removed
$clearedUsers = $zk->clearUsers();

// Remove a user from the ZKTeco device by UID
// Parameters:
// - integer $uid: User ID to remove
// Returns a boolean or mixed value indicating whether the user was successfully removed
$removedUser = $zk->removeUser($uid);

// Get the attendance log from the ZKTeco device
// Returns an array containing attendance log information
// Each entry in the array represents a single attendance record with fields: uid, id, state, timestamp, and type
$attendanceLog = $zk->getAttendance();

// Get the today attendance log from the ZKTeco device
// Returns an array containing attendance log information
// Each entry in the array represents a single attendance record with fields: uid, id, state, timestamp, and type
$attendanceLog = $zk->getTodaysRecords();


    public function zkteco()
    {
        $zk = new ZKTeco('192.168.1.201');
        $connected = $zk->connect();
        $attendanceLog = $zk->getAttendance();

        // Get today's date
        $todayDate = date('Y-m-d');

        // Filter attendance records for today
        $todayRecords = [];
        foreach ($attendanceLog as $record) {
            // Extract the date from the timestamp
            $recordDate = substr($record['timestamp'], 0, 10);

            // Check if the date matches today's date
            if ($recordDate === $todayDate) {
                $todayRecords[] = $record;
            }
        }

        // Now $todayRecords contains attendance records for today
        Log::alert($todayRecords); 
    }

// Get the 5 latest attendance records
$latestAttendance = $zk->getAttendance(5);

// Clear the attendance log from the ZKTeco device
// Returns a boolean or mixed value indicating whether the attendance log was successfully cleared
$clearedAttendance = $zk->clearAttendance();

// Parse raw fingerprint template data into structured format
// Returns array with template metadata and quality score
$parsedTemplate = $zk->parseFingerprintTemplate($rawTemplateData);

// Example response:
// [
//     'valid' => true,
//     'template_size' => 512,
//     'uid' => 123,
//     'finger_id' => 1,
//     'flag' => 1,
//     'template_data' => '...',
//     'quality_score' => 85
// ]

// Enroll a new fingerprint template for a user
// Parameters: uid, finger_id (0-9), template_data
$enrolled = $zk->enrollFingerprint(123, 1, $templateData);

// Retrieve face recognition templates for a user
// Returns array of face templates with quality scores
$faceData = $zk->getFaceData(123);

// Example response:
// [
//     50 => [
//         'template' => '...',
//         'size' => 1024,
//         'quality' => 92
//     ]
// ]

// Set face recognition templates for a user
$faceData = [
    50 => ['template' => $faceTemplateData]
];
$result = $zk->setFaceData(123, $faceData);

// Enroll a face recognition template for a user
// Automatically finds available slot
$enrolled = $zk->enrollFaceTemplate(123, $faceTemplateData);

// Retrieve the card number for a specific user
$cardNumber = $zk->getUserCardNumber(123);
// Returns: "1234567890" or false if not found

// Set advanced user role with granular permissions
$permissions = ['attendance', 'reports', 'user_management'];
$result = $zk->setUserRole(123, Util::LEVEL_ADMIN, $permissions);

// Get detailed role information for a user
$roleInfo = $zk->getUserRole(123);

// Example response:
// [
//     'role_id' => 14,
//     'role_name' => 'Administrator',
//     'permissions' => ['all_access', 'user_management', 'system_config'],
//     'can_enroll' => true,
//     'can_manage_users' => true,
//     'can_view_logs' => true
// ]

// Get all available user roles and their descriptions
$availableRoles = $zk->getAvailableRoles();

// Example response:
// [
//     0 => [
//         'name' => 'User',
//         'description' => 'Standard user with basic access',
//         'permissions' => ['attendance', 'view_own_records']
//     ],
//     14 => [
//         'name' => 'Administrator', 
//         'description' => 'Full administrative access',
//         'permissions' => ['all_access', 'user_management', 'system_config']
//     ]
// ]

// Get fingerprint template with quality assessment
$fingerprints = $zk->getFingerprint(123);
foreach ($fingerprints as $fingerId => $template) {
    $parsed = $zk->parseFingerprintTemplate($template);
    echo "Finger {$fingerId} quality: {$parsed['quality_score']}%";
}

// Get face templates with quality scores
$faceData = $zk->getFaceData(123);
foreach ($faceData as $faceId => $data) {
    echo "Face template {$faceId} quality: {$data['quality']}%";
}

// Display custom message on LCD screen
// Parameters: message, line (1-4), duration in seconds (0 = permanent)
$result = $zk->displayCustomMessage('Welcome John!', 1, 10);

// Display permanent message (until manually cleared)
$result = $zk->displayCustomMessage('System Maintenance', 2, 0);

// Clear all LCD content
$result = $zk->clearLCD();

// Open door remotely
$result = $zk->openDoor(1); // Door ID 1

// Close door remotely
$result = $zk->closeDoor(1);

// Lock door remotely
$result = $zk->lockDoor(1);

// Unlock door remotely
$result = $zk->unlockDoor(1);

// Get current door status
$status = $zk->getDoorStatus(1);

// Example response:
// [
//     'door_open' => true,
//     'door_locked' => false,
//     'sensor_active' => true,
//     'alarm_active' => false,
//     'timestamp' => '2024-10-01 15:30:45'
// ]

// Sync device time with server's default timezone
$result = $zk->syncTimeZone();

// Sync device time with specific timezone
$result = $zk->syncTimeZone('America/New_York');
$result = $zk->syncTimeZone('Europe/London');
$result = $zk->syncTimeZone('Asia/Tokyo');

// Get real-time events with timeout
$events = $zk->getRealTimeEvents(30); // 30 seconds timeout

// Example response:
// [
//     [
//         'type' => 'attendance',
//         'uid' => 123,
//         'timestamp' => '2024-10-01 15:30:45',
//         'state' => 1,
//         'raw_data' => '...' 
//     ]
// ]

// Start monitoring with custom callback
$callback = function($event) {
    echo "Event: {$event['type']} - User: {$event['uid']} - Time: {$event['timestamp']}\n";
    
    // Handle different event types
    switch($event['type']) {
        case 'attendance':
            // Process attendance event
            break;
        case 'door_open':
            // Handle door open event
            break;
        case 'alarm':
            // Handle alarm event
            break;
    }
};

// Start monitoring (runs for 60 seconds)
$zk->startEventMonitoring($callback, 60);

// Get event monitor instance for advanced handling
$monitor = $zk->getEventMonitor();

// Register specific event handlers
$monitor->on('attendance', function($event) {
    echo "Attendance event for user {$event['uid']}\n";
});

$monitor->on('door_open', function($event) {
    echo "Door opened by user {$event['uid']}\n";
});

$monitor->on('alarm', function($event) {
    echo "ALARM: {$event['timestamp']}\n";
    // Send notification, log to database, etc.
});

// Register handler for all events
$monitor->on('*', function($event) {
    // Log all events to database
    logEventToDatabase($event);
});

// Start monitoring
$monitor->start(); // Runs indefinitely

// Stop monitoring
$monitor->stop();

// Stop real-time event monitoring
$result = $zk->stopEventMonitoring();

// Door action constants
Util::DOOR_ACTION_OPEN    // Open door
Util::DOOR_ACTION_CLOSE   // Close door
Util::DOOR_ACTION_LOCK    // Lock door
Util::DOOR_ACTION_UNLOCK  // Unlock door

// Event type constants
Util::EVENT_TYPE_ATTENDANCE      // Attendance event
Util::EVENT_TYPE_DOOR_OPEN       // Door open event
Util::EVENT_TYPE_DOOR_CLOSE      // Door close event
Util::EVENT_TYPE_ALARM           // Alarm event
Util::EVENT_TYPE_USER_ENROLL     // User enrollment event
Util::EVENT_TYPE_USER_DELETE     // User deletion event
Util::EVENT_TYPE_SYSTEM_START    // System start event
Util::EVENT_TYPE_SYSTEM_SHUTDOWN // System shutdown event

// Initialize device
$zk = new ZKTeco('192.168.1.201');
$zk->connect();

// Check door status
$status = $zk->getDoorStatus(1);
if ($status['door_locked']) {
    // Unlock door for authorized access
    $zk->unlockDoor(1);
    $zk->displayCustomMessage('Door Unlocked', 1, 5);
}

// Open door
$zk->openDoor(1);

// Wait and close
sleep(10);
$zk->closeDoor(1);
$zk->lockDoor(1);

$zk->disconnect();

$zk = new ZKTeco('192.168.1.201');
$zk->connect();

$monitor = $zk->getEventMonitor();

// Set up event handlers
$monitor->on('attendance', function($event) {
    // Log attendance to database
    $user = getUserById($event['uid']);
    logAttendance($user, $event['timestamp'], $event['state']);
    
    // Display welcome message
    $zk->displayCustomMessage("Welcome {$user['name']}!", 1, 3);
});

$monitor->on('alarm', function($event) {
    // Send alert notifications
    sendSecurityAlert($event);
    
    // Display alarm message
    $zk->displayCustomMessage('SECURITY ALERT!', 1, 0);
});

// Start monitoring
$monitor->start();
ini
;extension=sockets
ini
    extension=sockets