PHP is a popular server-side scripting language used for developing dynamic web applications. To enable a PHP program to communicate with a remote server, a connection must first be established. This article explains step by step how to connect PHP to a server.
Use PHP's socket_create() function to create a socket:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
If successful, this function returns a socket resource handle.
Specify the server address and port you want to connect to:
$address = 'example.com'; $port = 80;
Use the socket_connect() function to connect the socket to the server:
$result = socket_connect($socket, $address, $port);
If the connection is successful, it returns true; otherwise, it returns false.
Send requests to the server using socket_write():
$data = 'GET /index.html HTTP/1.1\r\nHost: example.com\r\n\r\n'; $result = socket_write($socket, $data, strlen($data));
Use socket_read() to get the response from the server:
$data = '';
while (true) {
$buffer = socket_read($socket, 1024);
if (!$buffer) {
break;
}
$data .= $buffer;
}
After data transmission is complete, close the socket using socket_close():
socket_close($socket);
This article introduced the complete process of connecting PHP to a server, including socket creation, server connection, sending and receiving data, and closing the connection. Mastering these steps allows seamless communication between PHP and remote services.