How to Integrate Protocol Buffers with PHP over Binary TCP Sockets
This article explains how to add Protocol Buffer communication to a PHP web system, covering library setup, proto file adjustments, code generation, binary TCP handling with pack/unpack, and the switch from read_line to fread for reliable socket reads.
Our PHP web system needs to integrate a new service that communicates via the Protocol Buffer protocol, but only a C++ example is provided. PHP is not naturally suited for binary TCP socket communication.
PHP has an official Protocol Buffer implementation available at https://code.google.com/p/pb4php/ . When using the proto files supplied by the security center, two adjustments are required:
Comment out the package declaration in the header, which PHP cannot recognize.
Modify scalar types in the pb_parser file so that the generated PHP library can be built successfully.
After these changes, run the parser to generate the PHP library file pb_proto_scintf.php:
require_once('./parser/pb_parser.php'); $test = new PBParser(); $test->parse('scintf.proto');
We then write the actual program code. PHP can handle string‑based socket communication, but binary streams require conversion using pack and unpack. The pack function converts a string to a binary stream for transmission, and unpack converts the received binary data back to a string for processing ( http://php.net/manual/zh/function.pack.php ).
Initially we attempted to read socket responses with the internal read_line method (which internally uses fgets). This caused two problems:
When the TCP transmission contained only one packet, read_line read the whole content, but with multiple packets it only returned the first packet, leading to mismatched lengths during unpack. read_line reads until a newline, which binary streams do not contain, potentially causing socket timeouts.
The fix is straightforward: use fread, which works correctly with binary data.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
