RZ

Preparing your experience

Back to Blog
Backend Engineering

Talking to Biometric Attendance Devices over UDP from PHP: Inside the jmrashed/zkteco Package

November 22, 202612 min read
PHPLaravelUDPProtocolsOpen Source

Fingerprint, face and RFID attendance devices keep their punch logs inside the box. A web application that wants to read those punches, enrol a user or sync the clock needs a way to reach the device directly, over the network, without a separate desktop program in the middle. That is what I built jmrashed/zkteco for: an open-source PHP package, usable from Laravel, that talks to these devices over UDP. The repository was created in April 2024.

As of 22 November 2026, Packagist shows 28,534 total downloads (about 4,500 a month), and the GitHub repository has 69 stars and 25 forks. Downloads are not installs and stars are not production usage, so I treat those numbers as a sign that other people hit the same wall, not as proof of anything more. What I care about more is what the package taught me about talking to hardware. This post walks through how the protocol client works, using the actual source, and ends with the bugs that real devices forced me to fix.

Scope note: everything below describes the package's code at commit 4fd2ac2. I did not write the device protocol; the source itself says its checksum and time helpers were copied from the vendor's reference C code (zkemsdk.c). Device firmware varies, so treat the byte layouts as "what this parser reads", not as a specification.

1. The transport: plain UDP from PHP

The device speaks a binary protocol over UDP, by default on port 4370. PHP can do this with nothing but its sockets extension, which is why the package has no Laravel dependency in its core and the README's first setup step is enabling extension=sockets.

The constructor creates a datagram socket and sets a receive timeout of 60.5 seconds. That is a generous default, and it is a trade-off worth knowing about: UDP gives you no connection error when the other end is unreachable, busy or asleep, so you find out only by waiting for the timeout.

$this->_zkclient = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$timeout = ['sec' => 60, 'usec' => 500000];
socket_set_option($this->_zkclient, SOL_SOCKET, SO_RCVTIMEO, $timeout);

The first design consequence of UDP is that nothing is guaranteed: a datagram can be lost, duplicated or arrive out of order. The protocol compensates with a session id and a reply counter in every packet, which is the next piece.

2. Anatomy of a packet

Every message, in both directions, is an 8-byte header followed by an optional payload. The header is four unsigned 16-bit integers:

FieldSizePurpose
command2 bytesWhat to do, e.g. 1000 connect, 13 read attendance log, 2000 acknowledge
checksum2 bytesIntegrity check over the whole packet
session id2 bytesIssued by the device on connect; echoed on every later command
reply id2 bytesA counter that increases with every command and wraps at 65535

The library builds this with PHP's pack(). The one subtle point is that it uses the S format, which is the machine's own byte order. That is little-endian on the x86 and ARM servers PHP normally runs on, which is what the device expects, but it is a portability assumption worth knowing about.

static public function createHeader($command, $chksum, $session_id, $reply_id, $command_string)
{
    $buf = pack('SSSS', $command, $chksum, $session_id, $reply_id) . $command_string;
    $buf = unpack('C' . (8 + strlen($command_string)) . 'c', $buf);

    $chksum = unpack('S', self::createChkSum($buf))[1];

    $reply_id += 1;
    if ($reply_id >= self::USHRT_MAX) {
        $reply_id -= self::USHRT_MAX;
    }

    return pack('SSSS', $command, $chksum, $session_id, $reply_id) . $command_string;
}

The checksum treats the packet as a sequence of 16-bit words, adds them up, folds any overflow back into 16 bits, adds a trailing odd byte if there is one, then negates the result and subtracts one. It resembles the classic internet checksum with a vendor-specific twist, which is why the code copies the vendor's routine instead of reinventing it. With a binary protocol over UDP, a wrong checksum is the kind of mistake that is hard to diagnose, because the usual symptom is no reply at all. Test your packet builder against known-good packets before anything else.

3. The handshake and the session

A conversation starts with command 1000 (connect), sent with session id 0 and a reply id of 65534. The device answers with an acknowledgement whose header carries the session id it has assigned to you. The library reads bytes 4 and 5 of the reply, stores that number, and sends it with every command afterwards. An empty session id means the connect failed, even if some bytes came back.

$command = Util::CMD_CONNECT;      // 1000
$session_id = 0;
$reply_id = -1 + Util::USHRT_MAX;  // 65534

$buf = Util::createHeader($command, 0, $session_id, $reply_id, '');
socket_sendto($self->_zkclient, $buf, strlen($buf), 0, $self->_ip, $self->_port);
@socket_recvfrom($self->_zkclient, $self->_data_recv, 1024, 0, $self->_ip, $self->_port);

// session id = bytes 4-5 of the reply, little-endian
$session = hexdec($u['h6'] . $u['h5']);

One honest limitation lives in checkValid(). It accepts both 2000 (acknowledge OK) and 2005 (connection unauthorized) as success, with a TODO comment saying so. Some devices answer the connect with "unauthorized" when a communication password is set, and the library currently does not handle that authentication step. If your device has a comm key, this is where you will hit trouble.

4. Bulk data: a stream hidden inside datagrams

Small commands, such as reading the firmware version, get a single reply. The attendance log does not. When you send command 13 (read attendance log), the device does not reply with the data. It replies with command 1500 (CMD_PREPARE_DATA) whose payload is the total number of bytes it is about to send, and then it streams the data in datagrams of up to 1,032 bytes. The client's job is to keep reading until it has collected that many bytes.

$bytes = self::getSize($self);   // total size announced by CMD_PREPARE_DATA
$received = 0; $errors = 0;

while ($bytes > $received) {
    $ret = @socket_recvfrom($self->_zkclient, $dataRec, 1032, 0, $self->_ip, $self->_port);
    if ($ret === false) {
        if ($errors < $maxErrors) { $errors++; sleep(1); continue; }
        return '';               // give up after 10 failed reads
    }
    $data .= $dataRec;
    $received += strlen($dataRec);
}
// flush whatever trailing packet is left on the socket
@socket_recvfrom($self->_zkclient, $dataRec, 1024, 0, $self->_ip, $self->_port);

Two details matter here. First, a failed read is retried up to ten times with a one-second pause, because on a flaky network a missing datagram often means "slow", not "lost". Second, the trailing flush: the library reads and discards one more datagram after the data is complete, so a leftover packet cannot be mistaken for the reply to the next command. On a socket shared across many commands, a stray datagram left in the buffer makes every later reply one step out of line, which is a nasty class of bug to track down.

Parsing the records

Once the bytes are in, the parser skips the first 10 and walks the rest in 40-byte records. Reading the offsets in the current code, the fields it extracts are:

FieldWhere the parser reads itNotes
uidbytes 2-3 of the recordLittle-endian 16-bit internal user number
idbytes 4-12Badge or user id, null-padded text
statebyte 280 password, 1 fingerprint, 2 card
timestampbytes 29-32Little-endian, decoded with the time routine below
typebyte 330 check-in, 1 check-out, 4 overtime-in, 5 overtime-out

These offsets are the weak point of the whole library. They are read out of a hex string by position, and they fit the devices the package was developed against. Some other devices send the data differently, and the README lists "known device-specific parsing caveats". That is exactly what issue #7 ("Incorrect attendance data parsing id and timestamp") describes, and it is still open. The package's answer so far is an opt-in getSanitizedAttendance() that drops records failing basic sanity checks. It is deliberately opt-in so it cannot silently discard legitimate punches on devices that already parse correctly. The real fix needs raw packet captures from the affected devices.

5. The time format that is not a Unix timestamp

The device stores time as one integer, but not seconds since 1970. The formula, taken from the vendor reference code, packs the date as if every month had 31 days:

$d = (($year % 100) * 12 * 31 + (($month - 1) * 31) + $day - 1) * 86400
   + ($hour * 60 + $minute) * 60 + $second;

For 22 November 2026 at 10:00:00 that gives (26 x 372 + 10 x 31 + 21) x 86400 + 36000 = 864,295,200. Decoding reverses it with repeated division by 60, 60, 24, 31 and 12, then adds 2000 to the year. Two practical consequences follow. First, you cannot compare these raw numbers to Unix time or do date arithmetic on them. You must decode first. Second, the value carries no timezone. The package returns the device's wall-clock time as a string, which means a device whose clock is wrong, or set to a different zone than your server, produces records that look fine and are quietly off. Syncing the device clock with setTime() is the first thing I would do on any new installation.

6. Writing to the device: when a payload does not fit in one packet

Reading is the simpler half. Writing a fingerprint template to a device failed on real templates because templates are commonly 500 to 1,500 bytes or more, and the first version of the library sent the whole thing in a single UDP packet. Real templates simply did not arrive intact (issue #6, issue #11). The device has its own chunked upload protocol, the mirror image of the download one: announce the size, send the data in chunks, then issue the real command.

static public function sendWithBuffer(ZKTeco $self, $command, $data)
{
    if (strlen($data) <= self::MAX_CHUNK_SIZE) {          // 1024 bytes
        return $self->_command($command, $data);
    }

    $prepared = $self->_command(self::CMD_PREPARE_DATA, pack('V', strlen($data)));
    if ($prepared === false) { return false; }

    foreach (str_split($data, self::MAX_CHUNK_SIZE) as $chunk) {
        if ($self->_command(self::CMD_DATA, $chunk) === false) { return false; }
    }

    return $self->_command($command, '');                 // e.g. CMD_USER_TEMP_WRQ
}

The fix shipped in version 2.1.0. Small payloads still take the original direct path, so existing behaviour did not change. There is a test for it (SendWithBufferTest), and the lesson I took from it is general: any protocol that runs over datagrams has a size limit somewhere, and you only discover it when the first realistic payload exceeds it.

7. What real devices taught me

The 2.1.0 changelog is a good record of what only real devices and real users exposed. Each item below links to the original report.

  • Short or empty replies crash the parser. After a failed connect, the response was empty and unpack() threw "Type H: not enough input" (#2). The fix was a guard: check the length before unpacking. There is a dedicated test, ShortDataGuardTest, so it cannot regress.
  • A static/instance mismatch. getTodaysRecords() was fatal when called the documented way (#3). A reminder that README examples deserve tests too.
  • A limit that did not limit. getAttendanceWithLimit($limit) ignored its argument (#5, titled "slow"). It now honours the limit, but be clear about what that means: the protocol has no "give me the last N" command, so the library still downloads the whole log and slices it afterwards. getAttendanceByDateRange() works the same way. On a device with a year of punches, that is still a large transfer.
  • Disable the device while you talk to it. The README says to call disableDevice() before reading or writing and enableDevice() afterwards. Per the comments in Util.php, the disable command puts the device into a "shut-down" condition that shows an in-progress message on its screen, so if you skip enableDevice() the device stays unusable for the people standing at it.

8. How I would use it in production

The minimal flow is short, and the shape of it is the part worth copying:

composer require jmrashed/zkteco

use Jmrashed\Zkteco\Lib\ZKTeco;

$zk = new ZKTeco('192.168.1.201');      // default port 4370

if ($zk->connect()) {
    $zk->disableDevice();
    $log = $zk->getAttendance();         // uid, id, state, timestamp, type
    $zk->enableDevice();
    $zk->disconnect();
}

Around that flow I would add the things a library cannot decide for you:

  • Run it from a queue, not a web request. With a 60-second receive timeout and a log download that can be large, a request thread is the wrong place for it. A scheduled job that pulls and stores the log is.
  • Keep the device off the public internet. UDP with a session id and a checksum is an integrity check, not security. Put the device on an isolated network segment that only your application server can reach.
  • Store the raw log, then process it. Import every record into your own table keyed by uid and timestamp, and make the import idempotent so a retry cannot double-count a punch. Never treat the device as your system of record.
  • Always call enable and disconnect, even on failure. Put them in a finally block so one exception does not leave the device locked.

What I would improve next

Reading the code again for this post, three weak spots stand out. Record parsing by position in a hex string should become a small reader that is told which device layout to expect, with real packet captures kept as test fixtures. The authentication reply (2005) should be handled properly instead of sitting behind a TODO. And the date-range and limit helpers should say more loudly that they filter after a full download. None of this changes the main lesson: in a protocol client, the happy path is the small part. The network, the firmware variations and the edge cases are the rest of the work.

There is also a sibling project for Node.js, zk-attendance-sdk, that targets the same devices from TypeScript. If you have a device that parses wrongly, a packet capture attached to issue #7 is the most useful contribution anyone can make.

References

  1. jmrashed/zkteco repository: github.com/jmrashed/zkteco
  2. Package on Packagist: packagist.org/packages/jmrashed/zkteco
  3. Protocol constants, checksum, header builder, time encoding and chunked upload: src/Lib/Helper/Util.php
  4. Connect and disconnect handshake: src/Lib/Helper/Connect.php
  5. Attendance log parsing: src/Lib/Helper/Attendance.php
  6. Socket setup and the public API: src/Lib/ZKTeco.php
  7. Release notes for 2.1.0: CHANGELOG.md
  8. Issues discussed: #2, #3, #5, #6, #7, #11
  9. RFC 768, User Datagram Protocol: rfc-editor.org/rfc/rfc768
  10. PHP manual, Sockets: php.net/manual/en/book.sockets.php
  11. PHP manual, pack(): php.net/manual/en/function.pack.php
  12. Companion Node.js SDK: github.com/jmrashed/zk-attendance-sdk

Found this useful? Explore more articles on Backend Engineering.

All articles