PHP: Send data to host over TCP/IP

Useful for single quick operations on a host (like sending a command)

 * Sends data over TCP/IP to the specified host
 * and returns host reply (limited to 1024 chars)
 * @param string $hostIP
 * @param int $hostPort
 * @param string $data
 * @return string
private function sendDataToHost(string $hostIP, int $hostPort, string $data){
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $resp = "";
            socket_connect($socket, $hostIP, $hostPort);
            socket_write($socket, $data);
            $resp = socket_read($socket, 1024);
        }catch(\Exception $e){
            //Error while connecting socket
        //Error creating the socket
    return $resp;

Leave a Reply

Your email address will not be published. Required fields are marked *