Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Created December 12, 2020 06:05
Show Gist options
  • Save zonuexe/4b4604396f5278a15da7b0ea2a04bf27 to your computer and use it in GitHub Desktop.
Save zonuexe/4b4604396f5278a15da7b0ea2a04bf27 to your computer and use it in GitHub Desktop.
ソケットでHTTP/1.1通信する
<?php
$request = implode("\r\n", [
'POST /post HTTP/1.1',
'Host: httpbin.org',
'Accept: application/json',
'Content-Type: application/json',
'Connection: close',
'',
json_encode(['foo' => 'bar']),
]);
$ip = dns_get_record('httpbin.org', DNS_A)[0]['ip'];
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, $ip, 80) or die(socket_strerror(socket_last_error()));
echo $request, "\n\n------------------------------\n\n";
socket_write($sock, $request);
$response = '';
do {
$response .= ($buf = socket_read($sock, 2048));
} while ($buf !== '');
socket_close($sock);
echo $response;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment