I ran this code without any errors but the database is not updating. I am receiving the variable data from Paypal correctly. To verify the Post data I added two lines at the beginning of the script to write the variables to a text file. The server uses php 5.4. I hope you guys can find the problem.
<?php
/* checking for POST variables & writing to text file */
$posted_data = print_r($_POST,true);
file_put_contents('IPN_data.txt',$posted_data);
/*
Database config here
*/
/* Connect to database */
$conn = new mysqli($db_host, $db_user, $db_pass, $db_database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
//post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.1
";
$header .= "Content-Type: application/x-www-form-urlencoded
";
$header .= "Host: www.sandbox.paypal.com
";
$header .= "Connection: close
";
$header .= "Content-Length: " . strlen($req) . "
";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
//
$item = $_POST['item_name'];
$transaction_id = $_POST['txn_id'];
$payeremail = $_POST['payer_email'];
//error connecting to paypal
if (!$fp) {
//
}
//successful connection
if ($fp) {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
$res = trim($res); //NEW & IMPORTANT
if (strcmp($res, "VERIFIED") == 0) {
//insert order into database
if (strcmp ($payment_status, "Completed") == 0) {
/* update database */
if($item == 'Learn HTML'){
$sql = "INSERT INTO dc_html (transaction_id,email_id)
VALUES ( '$transaction_id','$payeremail')";
$conn->close();
break;
}
if($item == 'Learn Css') {
$sql = "INSERT INTO dc_css (transaction_id,email_id)
VALUES ( '$transaction_id','$payeremail')";
$conn->close();
break;
}
}
}
if (strcmp ($res, "INVALID") == 0) {
//insert into DB in a table for bad payments for you to process later
}
}
fclose($fp);
}
?>