title: Paypal IPN working but returns error status 500
body: <p>I'm having trouble with Paypal IPN. I'm using the IPN script from github:
  <a href="https://github.com/paypal/ipn-code-samples" rel="nofollow">Script link</a></p>
  
  <p>This is the php code for the script:</p>
  
  <pre><code>    &lt;?php
  // CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
  // Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
  // Set this to 0 once you go live or don't require logging.
  define("DEBUG", 1);
  
  // Set to 0 once you're ready to go live
  define("USE_SANDBOX", 0);
  
  
  define("LOG_FILE", "./ipn.log");
  
  
  // Read POST data
  // reading posted data directly from $_POST causes serialization
  // issues with array data in POST. Reading raw POST data from input stream instead.
  $raw_post_data = file_get_contents('php://input');
  $raw_post_array = explode('&amp;', $raw_post_data);
  $myPost = array();
  foreach ($raw_post_array as $keyval) {
      $keyval = explode ('=', $keyval);
      if (count($keyval) == 2)
          $myPost[$keyval[0]] = urldecode($keyval[1]);
  }
  // read the post from PayPal system and add 'cmd'
  $req = 'cmd=_notify-validate';
  if(function_exists('get_magic_quotes_gpc')) {
      $get_magic_quotes_exists = true;
  }
  foreach ($myPost as $key =&gt; $value) {
      if($get_magic_quotes_exists == true &amp;&amp; get_magic_quotes_gpc() == 1) {
          $value = urlencode(stripslashes($value));
      } else {
          $value = urlencode($value);
      }
      $req .= "&amp;$key=$value";
  }
  
  // Post IPN data back to PayPal to validate the IPN data is genuine
  // Without this step anyone can fake IPN data
  
  if(USE_SANDBOX == true) {
      $paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
  } else {
      $paypal_url = "https://www.paypal.com/cgi-bin/webscr";
  }
  
  $ch = curl_init($paypal_url);
  if ($ch == FALSE) {
      return FALSE;
  }
  
  curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
  
  if(DEBUG == true) {
      curl_setopt($ch, CURLOPT_HEADER, 1);
      curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
  }
  
  // CONFIG: Optional proxy configuration
  //curl_setopt($ch, CURLOPT_PROXY, $proxy);
  //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  
  // Set TCP timeout to 30 seconds
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
  
  // CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
  // of the certificate as shown below. Ensure the file is readable by the webserver.
  // This is mandatory for some environments.
  
  //$cert = __DIR__ . "./cacert.pem";
  //curl_setopt($ch, CURLOPT_CAINFO, $cert);
  
  $res = curl_exec($ch);
  if (curl_errno($ch) != 0) // cURL error
      {
      if(DEBUG == true) { 
          error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
      }
      curl_close($ch);
      exit;
  
  } else {
          // Log the entire HTTP response if debug is switched on.
          if(DEBUG == true) {
              error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
              error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
          }
          curl_close($ch);
  }
  
  // Inspect IPN validation result and act accordingly
  
  // Split response headers and payload, a better way for strcmp
  $tokens = explode("\r\n\r\n", trim($res));
  $res = trim(end($tokens));
  
  if (strcmp ($res, "VERIFIED") == 0) {
      // check whether the payment_status is Completed
      // check that txn_id has not been previously processed
      // check that receiver_email is your PayPal email
      // check that payment_amount/payment_currency are correct
      // process payment and mark item as paid.
  
      // assign posted variables to local variables
      //$item_name = $_POST['item_name'];
      //$item_number = $_POST['item_number'];
      //$payment_status = $_POST['payment_status'];
      //$payment_amount = $_POST['mc_gross'];
      //$payment_currency = $_POST['mc_currency'];
      //$txn_id = $_POST['txn_id'];
      //$receiver_email = $_POST['receiver_email'];
      //$payer_email = $_POST['payer_email'];
  
      if(DEBUG == true) {
          error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
      }
  } else if (strcmp ($res, "INVALID") == 0) {
      // log for manual investigation
      // Add business logic here which deals with invalid IPN messages
      if(DEBUG == true) {
          error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
      }
  }
  
  ?&gt;
  </code></pre>
  
  <p>...with my post-processing code being after the verifiy check</p>
  
  <pre><code>if (strcmp ($res, "VERIFIED") == 0) {
  </code></pre>
  
  <p>When someone pays via Paypal, everything seems to work in terms of my site receiving the IPN data and processing it. However, when I check the IPN logs in Paypal it has a status code of 500 (internal server error) and keeps resending the IPN data.</p>
  
  <p>I have no idea why this is happening. This same IPN script (or close variations) are all over the net so I presume the script is fine.</p>
  
  <p>Here is the log file recorded by the script:</p>
  
  <pre><code>[2015-08-15 13:31 Europe/London] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
  Host: www.paypal.com
  Accept: */*
  Connection: Close
  Content-Length: 1014
  Content-Type: application/x-www-form-urlencoded
  
   for IPN payload: cmd=_notify-validate&amp;mc_gross=4.95&amp;protection_eligibility=Eligible&amp;address_status=unconfirmed&amp;payer_id=--------&amp;tax=0.00&amp;address_street=------&amp;payment_date=05%3A25%3A51+Aug+15%2C+2015+PDT&amp;payment_status=Completed&amp;charset=windows-1252&amp;address_zip=------&amp;first_name=-----&amp;mc_fee=0.27&amp;address_country_code=ES&amp;address_name=-----&amp;notify_version=3.8&amp;custom=&amp;payer_status=verified&amp;business=--------&amp;address_country=Spain&amp;address_city=-------&amp;quantity=1&amp;verify_sign=AEWexEu2HAXvtIxtV.FjJ4XDJIdfA8MGuWBu9unU4dGBd7qVw2YL2a0p&amp;payer_email=--------&amp;txn_id=-------&amp;payment_type=instant&amp;payer_business_name=------&amp;last_name=W----&amp;address_state=------&amp;receiver_email=--------&amp;payment_fee=&amp;receiver_id=-------&amp;txn_type=web_accept&amp;item_name=---------&amp;mc_currency=GBP&amp;item_number=------&amp;residence_country=GB&amp;handling_amount=0.00&amp;transaction_subject=&amp;payment_gross=&amp;shipping=0.00&amp;ipn_track_id=--------
  [2015-08-15 13:31 Europe/London] HTTP response of validation request: HTTP/1.1 200 OK
  Server: Apache
  X-Frame-Options: SAMEORIGIN
  Paypal-Debug-Id: 85e8fa12ae5b4
  Cache-Control: max-age=0, no-cache, no-store, must-revalidate
  Pragma: no-cache
  Content-Type: text/html; charset=UTF-8
  DC: slc-origin-www.paypal.com
  Date: Sat, 15 Aug 2015 12:31:22 GMT
  Content-Length: 8
  Connection: close
  Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=GsUqRUQy6PV-FIg6NZNaoWTmld6up9P1KKqndXexz_jj_zeAZ4x0Kn30L4uIpy__dU4bnuACyaC89S34gzVIGmA2RmA8EBSoiH6oFumGT1YG-PxlbiMrDzyyNIjAnfFEJ0XPZmwovk7hutZlJannbvBOGibCAawKZ3rpqkphLxNrDZR-AZa0OAwjsUNEJtcy8gxroi8dbImfynYwQxhP_tTP1422-p2gLl8hxdhVqzO1PgDbCALd3kqfM67UCXZ0TVNpr5Pi84KsVZkZ1X00PblzKmbsFJ8vS7wbmocXEJveA6o1mPllq-qKO9MOEppBM0IxMS8rbwafRFDBzkFepW_gsNCkQPAATYNkLS6PTiBYMzL5-VV4ku_b4xTAsT_q4cotE5q4d-hqH1sE4fkdbql8HGCNwIiq2RpYrsI00nmMDrkGmZbHMV02BMG; domain=.paypal.com; path=/; Secure; HttpOnly
  Set-Cookie: cookie_check=yes; expires=Tue, 12-Aug-2025 12:31:22 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
  Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
  Set-Cookie: navlns=0.0; expires=Mon, 14-Aug-2017 12:31:22 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
  Set-Cookie: Apache=10.16.0.147.1439641881720232; path=/; expires=Mon, 07-Aug-45 12:31:21 GMT
  Set-Cookie: X-PP-SILOVER=name%3DLIVE9.WEB.1%26silo_version%3D880%26app%3Dappdispatcher%26TIME%3D422694741; domain=.paypal.com; path=/; Secure; HttpOnly
  Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
  Set-Cookie: Apache=10.16.0.206.1439641881713999; path=/; expires=Mon, 07-Aug-45 12:31:21 GMT
  Set-Cookie: AKDC=slc-origin-www.paypal.com; expires=Sat, 15-Aug-2015 13:01:22 GMT; path=/; secure
  Strict-Transport-Security: max-age=63072000
  
  VERIFIED
  </code></pre>
  
  <p>Does anyone know why I could be getting this 500 error?</p>
  
  <p>I've searched the net for a solution but can't find out what's wrong.</p>
  
  <p>Thanks    </p>