title: PayPal IPN Bad Request 400 Error
body: <p>Using the PayPal IPN, I keep getting an error 400.</p>
  
  <p>I have been making the script send me emails of <code>$res</code> to see what the response is, inside of the <code>while (!feof($fp)) {}</code> loop. I always end up getting the error: <code>HTTP/1.0 400 Bad Request</code></p>
  
  <p>In total I get back:</p>
  
  <pre><code>HTTP/1.0 400 Bad Request
  ​Connection: close
  Server: BigIP
  Content-Length: 19
  ​Invalid Host Header
  </code></pre>
  
  <p>​The last line after this is just blank. Here is my code, I have tried changing loads of things but nothing works.</p>
  
  <pre><code>$req = 'cmd=_notify-validate';
  foreach ($_POST as $key =&gt; $value) {
  $value = urlencode(stripslashes($value));
  $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}', $value);// IPN fix
  $req .= "&amp;$key=$value";
  }
  
  // post back to PayPal system to validate
  $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
  $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
  
  $fp = fsockopen('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
  
  if (!$fp) {
  // HTTP ERROR
  } else {
     fputs($fp, $header . $req);
     while (!feof($fp)) {
         $res = fgets ($fp, 1024);
         if (strcmp ($res, "VERIFIED") == 0) {
             //ADD TO DB
         } else if (strcmp ($res, "INVALID") == 0) {
             // PAYMENT INVALID &amp; INVESTIGATE MANUALY!
             // E-mail admin or alert user
         }
     }
     fclose ($fp);
  }
  </code></pre>
  
  <p>I have added a line, this is the header before it is sent:</p>
  
  <pre><code> Host: www.sandbox.paypal.com
   POST /cgi-bin/webscr HTTP/1.0
   Content-Type: application/x-www-form-urlencoded
   Content-Length: 1096
  </code></pre>