4

I have this strange problem that I'm receiving 400 Bad request as a response and I have absolutely no idea what's wrong with the header. Here's my code:

<?php

$sock = fsockopen('IP ADDRESS', 80, $errno, $errstr);

$header = array(
    'GET / HTTP/1.1',
    'Host: stackoverflow.com',
    'User-agent: My Useragent',
    'Connection: Close'
);

fputs($sock, join('\r\n', $header));

while(!feof($sock))
{
    echo fgets($sock, 128);
    break;
}

fclose($sock);

?>

Any ideas what I'm doing wrong?

Thanks

EDIT: Thanks to MrCode this problem was solved. Issue was here:

fputs($sock, join('\r\n', $header));

I had to change it to:

fputs($sock, join("\r\n", $header)."\r\n\r\n");

Notice double quotes and "\r\n\r\n"

Thanks again to MrCode

Jason
  • 113
  • 1
  • 4
  • 12
  • I had a similar problem where I was joining the headers with \n. That worked when connecting to older servers but started failing with newer servers. I guess \r\n is the standard and the newer servers were stricter about it. – arlomedia Jan 19 '18 at 00:11

1 Answers1

5

You're missing \r\n\r\n which is required after the final header. Currently you have nothing after the final header.

Append it to the join result:

fputs($sock, join("\r\n", $header) . "\r\n\r\n");

Also, you need to use double quotes around the \r\n because using single quotes causes PHP to take it literally and not as a new line.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • I tried it before too and I tried it now, but it still gives 400 error. http://pastebin.com/MspRazgG and a screenshot: http://puu.sh/feOE7/f86c88f098.png – Jason Jan 30 '15 at 17:01
  • Use double quotes not single. – MrCode Jan 30 '15 at 17:02
  • Well, that's awkward.. it worked now, thank you very much. I didn't know that this kind of things matter. – Jason Jan 30 '15 at 17:04