RZ

Preparing your experience

Back to Blog
Backend Engineering

jmrashed/zkteco Documentation: ZKTeco Attendance Devices in PHP and Laravel

November 29, 202610 min read
PHPLaravelZKTecoDocumentationOpen Source

This is the documentation for jmrashed/zkteco, my open-source PHP package for ZKTeco attendance devices. It works in plain PHP and in Laravel, and talks to the device over UDP. This guide covers version 2.1.1: installation, every main group of methods, what they return, a Laravel sync example, and the limits you should know before production.

This guide was written by reading the package source. Behaviour depends on your device model and firmware, so test on your own device. For how the protocol works inside, see Talking to Biometric Attendance Devices over UDP from PHP.

Contents

  1. Requirements and installation
  2. Quick start
  3. How return values work
  4. Device information and control
  5. Users, cards, roles and groups
  6. Attendance logs
  7. Fingerprint and face templates
  8. LCD, doors, time and real-time events
  9. Laravel example: syncing attendance
  10. Troubleshooting, security and known limitations

1. Requirements and Installation

  • PHP 8.1 or later. The tests run on PHP 8.1 to 8.5 on Linux.
  • The PHP sockets extension.
  • Laravel 11, 12 or 13 if you use Laravel. The core library does not depend on Laravel.
  • A network route from your server to the device over UDP, port 4370 by default.
composer require jmrashed/zkteco

If sockets are disabled, add extension=sockets to php.ini, restart PHP, and check with php -m. The command line and the web server can use different php.ini files, so check both.

A cloud server cannot reach a private address such as 192.168.1.201 by itself. Run the code inside the same network, or connect the two networks with a VPN.

2. Quick Start

use Jmrashed\Zkteco\Lib\ZKTeco;

$zk = new ZKTeco('192.168.1.201');        // port 4370
// $zk = new ZKTeco('192.168.1.201', 8080); // custom port

if (! $zk->connect()) {
    throw new RuntimeException('Cannot connect to the device');
}

try {
    $zk->disableDevice();                  // pause the device while reading
    $logs = $zk->getAttendance();
} finally {
    $zk->enableDevice();                   // always re-enable it
    $zk->disconnect();
}

The finally block matters. If your code fails after disableDevice(), you still want the device enabled again. There is no separate facade to register: create the ZKTeco class directly.

3. How Return Values Work

  • Simple commands such as enable, restart or set user return the raw reply payload as a string, or false. The payload can be an empty string, so compare with !== false instead of using a plain if.
  • A value other than false means a reply arrived for your session. These commands do not check the reply code, so verify important writes by reading the data back.
  • List methods such as getUser() and getAttendance() return an array. An empty array can mean "no data" or "the request failed".
  • The socket receive timeout is about 60 seconds, so an unreachable device can make a request wait. Use a queued job for web applications.
if ($zk->setTime(date('Y-m-d H:i:s')) !== false) {
    echo $zk->getTime();   // read back to confirm
}

4. Device Information and Control

MethodPurpose
connect(), disconnect()Open and close the session
version(), osVersion(), platform(), fmVersion()Version and platform information
serialNumber(), deviceName(), workCode()Serial number, name and work code
ssr(), pinWidth(), faceFunctionOn()Device settings
enableDevice(), disableDevice()Resume or pause normal use
restart(), shutdown(), sleep(), resume()Power control
testVoice()Play a test voice message

Information methods return the device reply as it arrives. It may contain a key name or null bytes, so clean the value before you store or show it. Be careful with shutdown(): you may need physical access to switch the device on again.

5. Users, Cards, Roles and Groups

Read users

getUser() returns an array keyed by userid:

[
    '108' => [
        'uid'      => 33,            // device record number
        'userid'   => '108',         // your ID, such as an employee number
        'name'     => 'John Doe',
        'role'     => 0,             // 0 = user, 14 = admin
        'password' => '',
        'cardno'   => '0001016618',  // 10 characters, zero padded
    ],
]

The result includes device passwords. Do not log it or send it to a browser.

Create, update and remove

use Jmrashed\Zkteco\Lib\Helper\Util;

// setUser($uid, $userid, $name, $password, $role, $cardno)
$zk->setUser(33, '108', 'John Doe', '', Util::LEVEL_USER, 1016618);

// same operation: an existing uid is overwritten
$zk->updateUser(33, '108', 'John D.', '', Util::LEVEL_USER, 1016618);

$zk->removeUser(33);   // takes the uid, not the userid
FieldLimit
uid1 to 65535
useridUp to 9 characters
nameUp to 24 bytes
passwordUp to 8 characters
cardnoUp to 10 digits, and no larger than 4294967295

The method returns false if a length or uid check fails. It does not reject a 10-digit card number above 4294967295, so check that yourself.

Fixed in 2.1.1: card numbers whose hexadecimal form had an odd number of digits were written incorrectly (for example, 1016618 was stored as 33578). getUser() also no longer adds a trailing space to cardno. If your code compares the old string, update it. If you wrote cards with an earlier version, read them back and write any wrong ones again. Thanks to Chandan Shakya for the fix.

getUserCardNumber($uid) returns one user's card number, or false if the user is not found.

clearUsers() and clearAdmin() are destructive. clearUsers() sends the device's general "clear data" command, so back up your data and try it on a test device first.

Roles

setUserRole($uid, $role) rewrites the user with a new role. It accepts a permissions array but does not send it to the device. getUserRole() and getAvailableRoles() return role descriptions defined inside the package, not permissions read from the device. Do not use them as your application's access control.

Groups

$zk->setUserGroup(33, 5);             // group ID 0 to 255
$zk->getUserGroup(33);
$zk->setGroupTimezones(5, [1, 2]);    // up to 3 time zone IDs
$zk->getGroupTimezones(5);

The group record layout has not been verified against a physical device capture.

6. Attendance Logs

MethodResult
getAttendance()All records
getAttendanceWithUser()Records plus user details
getAttendanceWithLimit(5)The last 5 records in the log
getAttendanceByDateRange($start, $end)Records in an inclusive range
getTodaysRecords()Records matching today's date in PHP
getSanitizedAttendance()Drops records that fail sanity checks
clearAttendance()Deletes the log on the device
[
    'uid'       => 33,
    'id'        => '108',
    'state'     => 1,                      // verification method
    'timestamp' => '2024-04-24 18:13:47',  // device time
    'type'      => 1,                      // punch type
]
  • state: 0 password, 1 fingerprint, 2 card. Other values show as "Unknown".
  • type: 0 check-in, 1 check-out, 4 overtime in, 5 overtime out. Use Util::getAttType($type) for a label.
  • With getAttendanceWithUser(), state_name is a label, type_name is the number as a string, and user is null if there is no match.
  • Limit and date filters run in PHP after the whole log has been downloaded. They do not make the transfer faster.
  • For getAttendanceByDateRange(), give a full end time such as 2024-01-31 23:59:59. A date alone means midnight at the start of that day.

Save and verify your copy before calling clearAttendance(). Punches can also arrive between your read and the clear command, so disable the device during that window.

7. Fingerprint and Face Templates

$fingers = $zk->getFingerprint(33);        // keyed by finger ID 0-9
$zk->setFingerprint(33, $fingers);         // returns number written
$zk->removeFingerprint(33, [0, 1]);        // returns number removed
$zk->enrollFingerprint(33, 1, $template);
$info = $zk->parseFingerprintTemplate($fingers[1]);

$faces = $zk->getFaceData(33);             // slots 50-54
$zk->setFaceData(33, [50 => ['template' => $faceTemplate]]);
$zk->enrollFaceTemplate(33, $faceTemplate); // first free slot

These methods move existing templates. They do not capture a new finger or face from the sensor. Fingerprint uploads larger than 1024 bytes are sent in chunks. Face uploads are sent as a single packet, so test large face templates carefully.

The quality_score and face quality values are simple estimates calculated in PHP from the data. They are not the device's biometric quality score, so do not use them to accept or reject a person.

Biometric templates are sensitive personal data. Get consent where required, follow your local law, encrypt stored templates and limit who can access them.

8. LCD, Doors, Time and Real-time Events

LCD

$zk->displayCustomMessage('Welcome', 1);   // line 1-4, up to 32 bytes
$zk->clearLCD();

If you pass a duration, the line is cleared when the PHP script shuts down, after sleeping for that time. It is not a background timer. writeLCD() writes a fixed text, so use displayCustomMessage() for your own message.

Doors

$zk->openDoor(1);
$zk->closeDoor(1);
$zk->lockDoor(1);
$zk->unlockDoor(1);

$status = $zk->getDoorStatus(1);
if (isset($status['error'])) {
    // handle the failure
}

Test door commands where a wrong result cannot lock anyone in or leave a secure area open. A software command should never replace a safe physical exit.

Time

$zk->getTime();                      // 'Y-m-d H:i:s'
$zk->setTime('2026-11-29 09:00:00');
$zk->syncTimeZone('Asia/Dhaka');     // sets the current time in that zone

Real-time events

$monitor = $zk->getEventMonitor();

$monitor->on('attendance', function (array $event) {
    // handle one punch
});

$monitor->on('*', function (array $event) {
    // handle every event
});

$monitor->start(60);   // blocks for about 60 seconds

Event names include attendance, door_open, door_close, alarm, user_enroll, user_delete, system_start and system_shutdown.

  • Windows: real-time events do not work in 2.1.1. The code uses MSG_DONTWAIT, which PHP on Windows does not define, so the call ends in an error. Run event monitoring on Linux.
  • Always pass a timeout. With 0 the loop runs without end, and calling stop() from a handler sends the stop command but does not exit the loop.
  • Run monitoring in a command-line worker, not in a web request.

9. Laravel Example: Syncing Attendance

Keep the device address in configuration:

// config/services.php
'zkteco' => [
    'ip'   => env('ZKTECO_IP'),
    'port' => (int) env('ZKTECO_PORT', 4370),
],

Add a table with a unique index so that running the sync again does not create duplicates:

Schema::create('attendance_punches', function (Blueprint $table) {
    $table->id();
    $table->string('device_ip', 45);
    $table->string('employee_code', 20);
    $table->dateTime('punched_at');
    $table->unsignedTinyInteger('state');
    $table->unsignedTinyInteger('type');
    $table->unique(['device_ip', 'employee_code', 'punched_at']);
});

Then add an Artisan command:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Jmrashed\Zkteco\Lib\ZKTeco;

class SyncAttendance extends Command
{
    protected $signature = 'attendance:sync';
    protected $description = 'Copy attendance records from the ZKTeco device';

    public function handle(): int
    {
        $ip = config('services.zkteco.ip');
        $zk = new ZKTeco($ip, config('services.zkteco.port'));

        if (! $zk->connect()) {
            $this->error('Cannot connect to the device');
            return self::FAILURE;
        }

        try {
            $zk->disableDevice();
            $records = $zk->getSanitizedAttendance();
        } finally {
            $zk->enableDevice();
            $zk->disconnect();
        }

        $rows = array_map(fn (array $r) => [
            'device_ip'     => $ip,
            'employee_code' => $r['id'],
            'punched_at'    => $r['timestamp'],
            'state'         => $r['state'],
            'type'          => $r['type'],
        ], $records);

        foreach (array_chunk($rows, 500) as $chunk) {
            DB::table('attendance_punches')->insertOrIgnore($chunk);
        }

        $this->info(count($rows) . ' records processed');
        return self::SUCCESS;
    }
}

Schedule it without overlapping runs:

// routes/console.php
Schedule::command('attendance:sync')->everyFiveMinutes()->withoutOverlapping();

Treat this as a starting point. getSanitizedAttendance() removes records that look corrupted, so compare it with getAttendance() on your device before relying on it, and never clear the device log based only on the filtered result.

10. Troubleshooting

ProblemWhat to check
Undefined function socket_create()Enable the sockets extension for the PHP that runs your code
connect() fails or waits a long timeIP, port, network route, VPN and UDP firewall rules. A successful ping does not prove UDP 4370 is open
connect() is true but reads are emptyThe device may require a Comm Key. The package has no way to send one, and connect() also returns true for an "unauthorized" reply
Strange IDs or datesYour model may use a different record format; see the known limitations
MSG_DONTWAIT errorReal-time events on Windows; run them on Linux
Deprecation notice from getUser()On PHP 8.2 and later, the package's use of utf8_encode() is deprecated

Security

  • This package does not encrypt the UDP traffic. Never expose the device port to the internet; keep devices on a private network or VPN.
  • If your device needs a Comm Key, changing that setting affects who can reach it. Restrict network access before you change anything.
  • Protect any route in your application that can change users, clear data or open doors, and keep an audit log.

Known Limitations

  • Some newer devices, such as the SpeedFace-V5L, can return incorrectly parsed attendance records (issues #7 and #12).
  • Real-time events do not work on Windows.
  • There is no Comm Key authentication.
  • The device log is downloaded in full before any filtering.
  • The user group layout is unverified.

Links and Contributing

If something behaves differently on your device, please open an issue with the model, firmware version and PHP version. Remove names, passwords and biometric data from anything you attach.

Found this useful? Explore more articles on Backend Engineering.

All articles