W3docs

How can I get the MAC and the IP address of a connected client in PHP?

You can use the $_SERVER['REMOTE_ADDR'] variable in PHP to get the IP address of a connected client.

You can use the $_SERVER['REMOTE_ADDR'] variable in PHP to get the IP address of a connected client. However, you cannot get the MAC address of a client using PHP alone, as the MAC address operates at the network layer and is not transmitted in HTTP request headers.

To retrieve a MAC address, you typically need direct access to the client's network interface, which requires a language or library that interacts with the OS (such as Java or Python's socket library). Alternatively, you can execute a system command like arp on the server, but this only works if the client is on the same local network. Note that the exec() function is often disabled by default in PHP for security reasons, so this approach may not work on shared hosting environments.

Here is an example of how you might use the arp command to attempt to get the MAC address of a client in PHP:

How to get the MAC and the IP address of a connected client in PHP?

<?php

// Get the client's IP address
$client_ip = $_SERVER['REMOTE_ADDR'];

// Note: arp only resolves MAC addresses for clients on the same local network.
// PHP_OS_FAMILY requires PHP 7.2+.
$escaped_ip = escapeshellarg($client_ip);
$command = PHP_OS_FAMILY === 'Windows' ? "arp -a $escaped_ip" : "arp -n $escaped_ip";
$exec_result = exec($command, $output, $return_var);

if ($return_var !== 0 || empty($output)) {
    echo "Failed to retrieve ARP information for $client_ip.";
} else {
    // Use regex to reliably extract the MAC address from arp output
    $mac_address = 'Not found';
    foreach ($output as $line) {
        if (preg_match('/([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})/', $line, $matches)) {
            $mac_address = $matches[0];
            break;
        }
    }
    echo "The MAC address for $client_ip is $mac_address";
}

Keep in mind that parsing arp output is highly OS-dependent and fragile. The example above assumes a specific output format and includes basic error handling. You may need to adjust the command and the parsing logic to match your server's environment.