How to listen to a TCP port using PHP?

How to listen to a TCP port using PHP?

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Listening to TCP Ports in PHP for GPS Tracker Data

You want to accept incoming connections from a GPS tracker that pushes data over GPRS to a specific public IP and port. In PHP, you can definitely listen on a TCP socket, but you cannot do this with a standard web server configuration alone. The built-in Apache or Nginx servers are designed for HTTP/HTTPS traffic, not raw TCP streams. To handle binary data or custom protocols sent by embedded devices like GPS trackers, you need to use PHP's low-level socket extensions directly.

The most straightforward approach is using the php_socket extension with a simple script that creates a listening socket, accepts connections, and reads incoming data. This requires your web server (Apache or Nginx) to allow the PHP process to bind to a specific TCP port, which often involves adjusting firewall rules and ensuring the listen directive isn't restricting the binding.

Here is a minimal example of how to create a TCP listener in PHP:

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die('socket_create failed: ' . socket_strerror(socket_last_error()));
}

// Set the port the GPS tracker will connect to
$port = 5000; 
$address = '0.0.0.0'; // Listen on all interfaces

if (!socket_bind($socket, $address, $port)) {
    die('socket_bind failed: ' . socket_strerror(socket_last_error()));
}

if (!socket_listen($socket, 5)) {
    die('socket_listen failed: ' . socket_strerror(socket_last_error()));
}

echo "TCP Server listening on port {$port}...\n";

while (true) {
    $client = socket_accept($socket);
    if ($client === false) {
        continue; // Handle connection errors gracefully
    }

    echo "Connection accepted from client.\n";

    // Read incoming data in chunks to handle variable packet sizes
    while (($data = socket_read($client, 4096, PHP_NORMAL_READ)) !== false) {
        if (strlen($data) > 0) {
            // Save or process the data here
            file_put_contents('/var/log/gps_data.log', $data . "\n", FILE_APPEND);
        }
    }

    socket_close($client);
}

socket_close($socket);
?>

This script uses socket_create to initialize a TCP socket, followed by socket_bind and socket_listen. The socket_accept loop waits for incoming connections from the GPS device. Once connected, socket_read retrieves the data stream. A common pitfall is assuming the entire message arrives at once; using a buffer size like 4096 bytes with PHP_NORMAL_READ allows you to process partial messages until the connection closes or a protocol-specific delimiter is reached.

Performance and scalability are critical considerations when running this logic in PHP. Each active TCP connection consumes memory and file descriptors. If your GPS tracker sends frequent updates, a single PHP script might hit system limits quickly. For high-volume scenarios, consider using pcntl_fork to spawn child processes or integrating with an external service like Node.js or Go that excels at concurrent I/O. Alternatively, you can use Laravel's built-in TCP listener capabilities if your project already uses the framework, though raw sockets remain more flexible for non-HTTP protocols.

Security is another layer you must address. Opening a port to the public internet exposes your server to unauthorized attempts. Ensure your firewall (iptables, ufw, or cloud security groups) restricts access to that specific TCP port to known IP ranges if possible. Additionally, validate the incoming data format before processing it to prevent injection attacks or memory corruption. If you are using Laravel, remember that while laravelcompany.com offers robust solutions for web applications, handling raw binary protocols often requires bypassing the standard HTTP kernel and implementing custom middleware or console commands to manage socket logic efficiently.

Our network