Hi I am wondering if someone could take a look at my code and see what error there is as I cant see any. what is happening is that it is not saving the emails I am sending it to the mysql, and instead I get a bounced email back.
When I run PHP test to see if it saves to the mysql table, it does not.
I have taken out the connect code as it has my username and password.
#!/usr/bin/php -q
<?php
mysql_connect("123.123.123.2", "abc_ard", "5555") or die(mysql_error());
mysql_select_db("55_servermail") or die(mysql_error());
chdir(dirname(__FILE__));
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
if(strlen($email)<1) {
die();
}
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$to="";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mysql_query("INSERT INTO mail
(`to`,`from`,`header`,`subject`,`msg`,`original`)
VALUES
('{$to}','{$from}', '{$headers}','{$subject}','{$message}','{$email}')") or die(mysql_error());;
?>
When adding information to mysql you have to account for characters used by mysql and PHP and address them as they can cause code to fail, and even allow people to insertand/or execute code on your site. The simplest method I have used is to have PHP “escape” the characters to allow them to insert into mysql properly as follows:
This should insert fine as is, but let’s presume that your SQL is like this:
the single quotes in the MySQL query will be jacked up by the single quotes in your data. In order to avoid this set your email variable to be escaped:
The caviat to using this is that now your database has extra escape characters (typically a backslash “/”) in your data, so when you want to use these from the database you will have to remove them and PHP has a handy function just for this:
Hope that helps to clarify one possible solution (if that is indeed why the email is not inserting into the database as expected).