0

I'm trying to get an http response from this script in a browser, why doesn’t it work?

$http = "HTTP/1.1 404 Not Found";
$http .= "Host: localhost";
$http .= "Connection: close";

$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, '0.0.0.0', 80);
socket_listen($sock);

while (1 == 1)
{
  $s = socket_accept($sock);
  socket_write($s,$http,strlen($http));
}
ArSeN
  • 5,133
  • 3
  • 19
  • 26
  • Does this answer your question? [difference between socket programming and Http programming](https://stackoverflow.com/questions/15108139/difference-between-socket-programming-and-http-programming) – ArSeN Jan 17 '20 at 20:22
  • What are the actual symptoms you're seeing? Since this only has headers, I wouldn't expect browsers to do much. – Evert Jan 17 '20 at 21:56
  • [From the docs](https://www.php.net/manual/en/function.socket-write.php): `Note: It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.` -- What is the return value of this operation? – Matt Clark Jan 17 '20 at 22:02
  • Also remember that the HTTP protocol has 2x new lines after the last byte to indicate EOM. It's possible that whatever you are using to fetch the data is hanging looking for this EOM which has not been sent by the server - i.e., your response is not a valid HTTP response. – Matt Clark Jan 17 '20 at 22:03
  • 1
    Actually, you don't even have new line characters between your header lines. You response to the client would be: `HTTP/1.1 404 Not FoundHost: localhostConnection: close` all as a single line. – Matt Clark Jan 17 '20 at 22:04
  • I solved my problem by formatting the headers and clearing the cache in chrome. Now everything works. ```$http = "HTTP/1.1 403 Forbidden\r\n"; $http .= "Host: localhost\r\n"; $http .= "Connection: close\r\n\r\n";``` –  Jan 18 '20 at 05:19

0 Answers0