// create a socket, look up the remote address, and connect to it $host = 'example.com'; $port = 80; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $address = gethostbyname($host); socket_connect($socket, $address, $port); // send a request to the server and retrieve the response $request = "GET / HTTP/1.1\r\nHost: $host\r\n\r\n"; socket_write($socket, $request, strlen($request)); $response = socket_read($socket, 1024); // display the response echo $response; // close the connection socket_close($socket);
// create a socket, and bind it to any available local port $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_bind($socket, '0.0.0.0', 0); // send a message to the server, and wait for the response $message = 'Hello, server!'; $serverAddress = '127.0.0.1'; $serverPort = 8888; socket_sendto($socket, $message, strlen($message), 0, $serverAddress, $serverPort); socket_recvfrom($socket, $response, 1024, 0, $serverAddress, $serverPort); // display the response echo $response; // close the socket socket_close($socket);Here, we create a UDP socket, bind it to a local port, and send a message to a server. We then wait for the response and display it. The package library used here is again PHP's built-in socket extension. In conclusion, the built-in socket extension in PHP provides a simple and effective way to create internet-based applications that can communicate with other internet-based applications.