My php mail function is sending blank messages - php

So as the title states I receive blank emails from my contact form. The php code is below. I've checked the value of $msg and it appears correctly, I've also googled a ton and I can't find anything standard cause that apply to me.
<?php
main();
function main() {
$posted = setVariables();
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);
}
function setVariables() {
$name;
if (isset($_POST['name'])){
$name=$_POST['name'];
if ($name == null) {
$name = "ERROR - name is null";
}
}
$email;
if (isset($_POST['email'])){
$email=$_POST['email'];
if ($email == null) {
$email = "ERROR - email is null";
}
}
$enquiry;
if (isset($_POST['enquiry'])){
$enquiry=$_POST['enquiry'];
if ($enquiry == null) {
$enquiry = "ERROR - enquiry is null";
}
}
$message;
if (isset($_POST['message'])){
$message=$_POST['message'];
if ($message == null) {
$message = "ERROR - message is null";
}
}
$posted = array($name,$email,$enquiry,$message);
return $posted;
}
function setMessage($posted) {
$msg = "Name: " . $posted[0] . "\r\nEmail: " . $posted[1] . "\r\nEnquiry: " . $posted[2] . "\r\nMessage: " . $posted[3];
$msg = wordwrap($msg,70);
$msg = Trim(stripslashes($_POST['Message']));
return $msg;
}
function sendMail($msg) {
$result = mail("social#georgeappleton.co.uk","Contact From Portfolio",$msg, "From: <info#yourdomain.co.uk>");
return $result;
}
function userFeedback($result) {
if ($result == false) {
echo "Message failed to send, please inform me through my email address. social#georgeappleton.co.uk";
} else {
echo "Message Sent!<br/><br/>Returning you to <a href='http://www.georgeappleton.co.uk'>georgeappleton.co.uk</a> in 5 seconds";
}
echo "<script>setTimeout(function() {window.location = 'http://www.georgeappleton.co.uk';},5000);</script>";
}
?>
Thanks guys, appreciate it a lot
-Shardj

Get rid of this line:
$msg = Trim(stripslashes($_POST['Message']));
It's overwriting $msg with the contents of a nonexistent parameter. It already contains the message text, which was in $posted[3].

It's your variable scope. $name withing setVariables()
$name=$_POST['name'];
if (strlen($name) < 1) {$name = "ERROR - name is null";}
$email=$_POST['email'];
if (strlen($email) < 1) {$email = "ERROR - email is null";}
$enquiry=$_POST['enquiry'];
if (strlen($enquiry) < 1) {$enquiry = "ERROR - enquiry is null";}
$posted = array($name,$email,$enquiry,$message);
$msg = setMessage($posted);
$result = sendMail($msg);
userFeedback($result);

Related

undefined variable login message

I have this registration page, and I call the method reg_check() on $user. I get errors messages, and they are displayed if some inputs haven't been filled. But when I fill all of it I get an error message "undefined variable".
I tried to put $message=" " in different places in method and regPage but still getting error: undefined variable login message
This is on registration page:
if(isset($_POST['submit'])){
//$message = "";
$user->reg_check();
}else
{
$message = "";
}
?>
Problem on this line:
NOTICE: UNDEFINED VARIABLE: MESSAGE IN...
<h4 class="bg-danger"><?php echo $message; ?></h4>
reg_check method
public function reg_check()
{
global $baza;
switch(isset($_POST)){
case empty($_POST['pass']):
// header( "refresh:4;url=reglog.php" );
$message = "Upišite šifru u odgovorajuće polje";
break;
case ($_POST['pass']<5):
// header( "refresh:4;url=reglog.php" );
$message = "Vaša šifra mora biti duža od 5 karaktera";
break;
case empty($_POST['email']):
// header( "refresh:4;url=reglog.php" );
$message = "Upišite mail u odgovarajuće polje";
break;
case isset($_POST['email']):
$email = $baza->sanitize($_POST['email']);
$cmail=['mail'=>$email];
$postoji = $baza->prep_query("SELECT email FROM users WHERE email = :mail limit 1",$cmail);
$count= count($postoji->fetch(PDO::FETCH_OBJ));
if($postoji->rowCount() > 0){
// header( "refresh:4;url=reglog.php" );
$message = "Korisnik sa email: " . $email . " već postoji!";
}
else
{ $message = "";
$this->registration($_POST);
}
break;
}
}
In order to access a variable defined and set inside you class. You need to get it out of the box with a method. You have one already $message. The only thing you need to do is return it. So that when you call the mehtod reg_check(), you get a value (the message). That way you can retrieve variables from inside your class.
<?php
public function reg_check()
{
global $baza;
switch(isset($_POST)){
case(empty($_POST['pass'])):
// header( "refresh:4;url=reglog.php" );
$message = "Upišite šifru u odgovorajuće polje";
break;
case($_POST['pass'] < 5):
// header( "refresh:4;url=reglog.php" );
$message = "Vaša šifra mora biti duža od 5 karaktera";
break;
case(empty($_POST['email'])):
// header( "refresh:4;url=reglog.php" );
$message = "Upišite mail u odgovarajuće polje";
break;
case(isset($_POST['email'])):
$email = $baza->sanitize($_POST['email']);
$cmail=['mail'=>$email];
$postoji = $baza->prep_query("SELECT email FROM users WHERE email = :mail limit 1",$cmail);
$count= count($postoji->fetch(PDO::FETCH_OBJ));
if($postoji->rowCount() > 0) {
// header( "refresh:4;url=reglog.php" );
$message = "Korisnik sa email: " . $email . " već postoji!";
} else {
$message = "";
$this->registration($_POST);
}
break;
}
// when all of the switch() case: as been done return the message
return $message;
}
Then on any file where you have defined $user as a new instance of you class. You can call in the method and get in return a value.
<?php
if(isset($_POST['submit'])) {
// echo the value returned by the method `reg_check()`
$message = $user->reg_check();
} else {
$message = '';
}
echo $message;
Or in one line
echo isset($_POST['submit']) ? $user->reg_check() : '';
Since your defining a new $message ina function you should return the result back again. Like this
if(isset($_POST['submit'])){
$message = $user->reg_check();
}
public function reg_check()
{
.....
return $message;
}
Or just do echo $user->reg_check();
Initializing $message to an Empty string in your method should be enough. And you should not forget to return your $message at the end of your method...
<?php
public function reg_check(){
global $baza;
$message = "";
switch(isset($_POST)){
case empty($_POST['pass']):
$message = "Upišite šifru u odgovorajuće polje";
break;
case ($_POST['pass']<5):
$message = "Vaša šifra mora biti duža od 5 karaktera";
break;
case empty($_POST['email']):
$message = "Upišite mail u odgovarajuće polje";
break;
case isset($_POST['email']):
$email = $baza->sanitize($_POST['email']);
$cmail =['mail'=>$email];
$postoji = $baza->prep_query("SELECT email FROM users WHERE email = :mail limit 1",$cmail);
$count = count($postoji->fetch(PDO::FETCH_OBJ));
if($postoji->rowCount() > 0){
$message = "Korisnik sa email: " . $email . " već postoji!";
}else {
$this->registration($_POST);
}
break;
}
// YOU MUST RETURN $message AS IT IS NECESSARY IN YOUR CASE....
return $message;
}
?>
<?php
$message = "";
if(isset($_POST['submit'])){
$user->reg_check();
}
?>
<h4 class="bg-danger"><?php echo $message; ?></h4>

PHP checkboxes won't send Yes/No values in email

I'm trying to familiarize myself with PHP by making a simple pizza ordering system that emails size, toppings, and the orderer's information. The email sends nicely, but the toppings section of the email is blank. What am I missing?
Thanks!
<?php
/* Set e-mail recipient */
$myemail = "katrina.skovan#gmail.com";
$subject = "Pizza Order";
/* Check all form inputs using check_input function */
$name = check_input($_POST['name'], "Enter your name");
$email = check_input($_POST['email'], "Enter your email");
$street = check_input($_POST['street'], "Enter your your street");
$apt = check_input($_POST['apt'], "Enter your your apartment number");
$zip = check_input($_POST['zip'], "Enter your ZIP code");
$phone = check_input($_POST['phone'], "Enter your phone number");
$comments = $_POST['comments'];
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
if(isset($_POST['Half Pepperoni']) &&
$_POST['halfpepperoni'] == 'Yes')
{
echo "halfpepperoni";
}
else
{
echo "";
}
if(isset($_POST['Onions']) &&
$_POST['onions'] == 'Yes')
{
echo "onions";
}
else
{
echo "";
}
if(isset($_POST['Half Onions']) &&
$_POST['halfonions'] == 'Yes')
{
echo "halfonions";
}
else
{
echo "";
}
if(isset($_POST['Mushrooms']) &&
$_POST['mushrooms'] == 'Yes')
{
echo "mushrooms";
}
else
{
echo "";
}
if(isset($_POST['Half Mushrooms']) &&
$_POST['halfmushrooms'] == 'Yes')
{
echo "halfmushrooms";
}
else
{
echo "";
}
if(isset($_POST['Peppers']) &&
$_POST['peppers'] == 'Yes')
{
echo "peppers";
}
else
{
echo "";
}
if(isset($_POST['Half Peppers']) &&
$_POST['halfpeppers'] == 'Yes')
{
echo "halfpeppers";
}
else
{
echo "";
}
if(isset($_POST['Extra Cheese']) &&
$_POST['extracheese'] == 'Yes')
{
echo "extracheese";
}
else
{
echo "";
}
if(isset($_POST['Half Extra Cheese']) &&
$_POST['halfextracheese'] == 'Yes')
{
echo "halfextracheese";
}
else
{
echo "";
}
if(isset($_POST['Sausage']) &&
$_POST['sausage'] == 'Yes')
{
echo "sausage";
}
else
{
echo "";
}
if(isset($_POST['Half Sausage']) &&
$_POST['halfsausage'] == 'Yes')
{
echo "halfsausage";
}
else
{
echo "";
}
/* Let's prepare the message for the e-mail */
/* -=-=-=- EDITED -=-=-=- The toppings should be uncommented BUT you need to make variables like above Likewise the checkboxes need to have associated.
here's annother example variable:
$pepperoni = $_POST['pepperoni'];
*/
$message = "
Toppings:
$pepperoni
$halfpepperoni
$onions
$halfonions
$mushrooms
$halfmushrooms
$peppers
$halfpeppers
$extracheese
$halfextracheese
$sausage
$halfsausage
Name: $name
Email: $email
Street: $street
Apt: $apt
ZIP: $zip
Phone: $phone
Comments: $comments
";
$headers = "From:" . $email;
/* Send the message using mail() function */
/*mail($name, $email, $apt, $zip, $phone, $comments $pepperoni $halfpepperoni $onions $halfonions $mushrooms $halfmushrooms $peppers $halfpeppers $extracheese $halfextracheese $sausage $halfsausage);*/
mail($myemail,$subject,$message,$headers);
/* Redirect visitor to the thank you page */
header('Location: thanks.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<p>Please correct the following error:</p>
<strong><?php echo $myError; ?></strong>
<p>Hit the back button and try again</p>
</body>
</html>
<?php
exit();
}
?>
Replace all space between the textfield name, Ex: use halfonions instead of using textname with space like Half Onions
if(isset($_POST['halfonions']) && $_POST['halfonions'] == 'Yes') {
instead of
if(isset($_POST['Half Onions']) && $_POST['halfonions'] == 'Yes') {
You are not setting your variables, you are only echoing them out:
/* the following code is currently not working */
$pepperoni = $_POST['pepperoni'];
if(isset($_POST['pepperoni']) &&
$_POST['Pepperoni'] == 'Yes')
{
echo "pepperoni";
}
else
{
echo "";
}
Now the $pepperoni variable will contain Yes if it was selected and nothing else. And that is the only variable you are currently trying to set, the rest of the variables in your message is undefined.
You probably want something like:
if(isset($_POST['pepperoni']) &&
$_POST['pepperoni'] == 'Yes')
{
$pepperoni = "pepperoni";
}
else
{
$pepperoni = "";
}
And that for all the variables you use in your message.
And you can reduce that to:
$pepperoni = isset($_POST['pepperoni']) ? 'pepperoni' : '';
^ or however it is spelled in the html...
as the value does not really matter.
I think there are spaces in the variables like "Half Pepperoni" or "Half Mushrooms" !!

Wordpress Help Redirect after form submission

I want to have my contact form redirect after form submission. I don't know how do it. This is my code and also it's giving me an error.
<?php
// If the form is submitted
if(isset($_POST['submit'])) {
// Include WordPress Core Functions
$wp_include = '../wp-load.php';
while(!#include_once($wp_include)) { $wp_include = '../'.$wp_include; }
//
// Field Validation
//
// Check to make sure that the name field is not empty
if(trim($_POST['cf_name']) == '') {
$has_error = true;
}
else {
$name = trim($_POST['cf_name']);
}
// Check to make sure that the subject field is not empty
if(trim($_POST['cf_subject']) == '') {
$has_error = true;
}
else {
$subject = trim($_POST['cf_subject']);
}
// Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$has_error = true;
}
elseif(!preg_match("/^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$has_error = true;
}
else {
$email = trim($_POST['email']);
}
// Check to make sure comments were entered
if(trim($_POST['cf_message']) == '') {
$has_error = true;
}
else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['cf_message']));
}
else {
$message = trim($_POST['cf_message']);
}
}
//
// Send E-Mail
//
// Send the email if there is no error
if(!isset($has_error)) {
// Get recheiver
$receiver = ($_POST['cf_receiver']) ? $_POST['cf_receiver'] : get_option('admin_email');
$receiver = str_replace('[at]', '#', $receiver);
// Headers
$headers = "From: $name <$email>\n";
$headers.= "Content-Type: text/plain; charset=\"UTF-8\"\n";
// Message
if($_POST['cf_email_signature'] && $_POST['cf_email_signature'] != 'none') {
$message.= "\n\n---\n".$_POST['cf_email_signature'];
}
// Send E-Mail
$mail_sent = wp_mail($receiver, $subject, $message, $headers);
if($mail_sent)
echo "<p class='info-box success'>".$_POST['cf_success_msg']."</p>";
else
echo "<p class='info-box error'>The message couldn't be sent because an internal error occured.</p>";
echo "<p class='info-box error'>".$_POST['cf_error_msg']."</p>";
}
}
?>
The function for a redirect in wordpress is wp_redirect, e.g.
if( $mail_sent ) {
wp_redirect( '/my-target' );
exit();
} else {
//output your warning
}

Mail could not be send using php

Hope all of my experts are fine. Buddy's i stuck in a very simple code. Actually i have to insert a form and then fetch values from it to send mail to the user who fills the form. All the values are inserting into the database and also fetch from database but mail is not sending. The same code was sending mail one day ago. But today it is not sending mail. Please help me out in this.
<?php
require("dbconnect.php");
require("DBConnection.php");
session_start();
if(isset($_POST['postadd'])){
$title = $_POST['adtitle'];
$area = $_POST['area'];
$addesc = $_POST['addesc'];
$email = $_POST['email'];
$showemail = $_POST['showemail'];
$userpic = ($_FILES['pic1']['tmp_name']);
$compath = "UploadPictures/".md5($_FILES['pic1']['name']);
$comFileType=$_FILES['pic1']['type'];
$comFileSize=$_FILES['pic1']['size'];
$comFileSize=$comFileSize/1024;
if($comFileSize<1000)
{
$arrFileType=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType,$arrFileType))
{
move_uploaded_file($userpic,$compath);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic2 = ($_FILES['pic2']['tmp_name']);
$compath2 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType2=$_FILES['pic2']['type'];
$comFileSize2=$_FILES['pic2']['size'];
$comFileSize2=$comFileSize2/1024;
if($comFileSize2<1000)
{
$arrFileType2=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType2,$arrFileType2))
{
move_uploaded_file($pic2,$compath2);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic3 = ($_FILES['pic3']['tmp_name']);
$compath3 = "UploadPictures/".md5($_FILES['pic2']['name']);
$comFileType3=$_FILES['pic3']['type'];
$comFileSize3=$_FILES['pic3']['size'];
$comFileSize3=$comFileSize3/1024;
if($comFileSize3<1000)
{
$arrFileType3=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType3,$arrFileType3))
{
move_uploaded_file($pic3,$compath3);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$pic4 = ($_FILES['pic4']['tmp_name']);
$compath4 = "UploadPictures/".md5($_FILES['pic4']['name']);
$comFileType4=$_FILES['pic4']['type'];
$comFileSize4=$_FILES['pic4']['size'];
$comFileSize4=$comFileSize4/1024;
if($comFileSize4<1000)
{
$arrFileType4=array("image/jpeg","image/png","image/gif","image/bmp");
if(in_array($comFileType4,$arrFileType4))
{
move_uploaded_file($pic4,$compath4);
}
else
{
("Invalid Image Format");
}
}
else
{
("File Size Error");
}
$agree = $_POST['checkbox'];
$subcat = $_SESSION['subcat'];
$cat = $_SESSION['cat'];
$rand = rand();
$datecreated = date("Y-m-d h:i:s");
$obj = new DBConnection();
$arr_Field = array("title","location","post","email","radio","pic1","pic2","pic3","pic4","agree","cat","subcat","random","datecreated");
$arr_values = array("$title","$area","$addesc","$email","$showemail","$compath","$compath2","$compath3","$compath4","$agree", "$cat", "$subcat" ,"$rand","$datecreated");
$obj->InsertRecord("ads",$arr_Field,$arr_values) or die (mysql_error());
$object = new DBConnection();
$condition = "ORDER BY id DESC LIMIT 1";
$selquery = $object->SelectRecord(array("*"),"ads","$condition") or die(mysql_error());
while($get = mysql_fetch_array($selquery)){
$email = $get['email'];
$id = $get['id'];
}
//echo $email;
//exit();
$to = $email;
$subject = "Admin";
$message = "
<html>
<head>
<title>Admin</title>
</head>
<body>
<p>Please Click on this Link to verify your post</p>
<p><a href='http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."'>http://almughnisolutions.com/almughniclassified/summary.php?summary=".$id."</a></p>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <admin#almughniclassfied.com>' . "\r\n";
mail($to,$subject,$message,$headers) or die("Mail Cannot sent");
//header("Location:verifyadd.php");
}
?>
It would probably be a safe assumption that your code is not to blame. A cursory review of it seems like it shuold work if the SMPT server is behaving correctly. I would recommend testing the server. There are a some web based tools to do this:
https://www.wormly.com/test_smtp_server
You could also just use telnet to test from your machine if it's something that will need to be done internally:
http://technet.microsoft.com/en-us/library/aa995718%28v=exchg.65%29.aspx

having the hardest time passing NULL to my database

im working on a part of program where i need to send null to my database if the textbox is empty here is what i have so far
<?php
//so if not connected to database it displays an error message instead of a php error recommend having on 1 in development mode - for warnings and error
ini_set( "display_errors", 0);
if(!$_POST) exit;
$con = mysql_connect("localhost","imstillr","password");
mysql_select_db("imstillr_crm", $con);
$company = protect($_POST['company']); //required
$primarycontact = protect($_POST['primarycontact']); //required
$primaryemail = protect($_POST['primaryemail']); //required
$preferphone = protect($_POST['preferphone']); //required
$secondarycontact = protect($_POST['secondarycontact']);
$secondaryemail = protect($_POST['secondaryemail']);
$optionalphone = protect($_POST['optionalphone']);
$department = protect($_POST['department']);
$website = protect($_POST['website']); //required*/
//database info
mysql_query("SELECT companyname FROM customerinfo WHERE companyname='" .$company. "'");
if (!$con)
{
//checks if database connection string is correct
echo '<div class="error_message">Attention! no database connection.</div>';
exit();
} else if(mysql_affected_rows() == 1) {
echo '<div class="error_message">Attention! This company already exists.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! You must enter your company name.</div>';
exit();
} else if(trim($primarycontact) == '') {
echo '<div class="error_message">Attention! You must enter a contact name.</div>';
exit();
} else if(trim($primaryemail) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($primaryemail)) {
echo '<div class="error_message">Attention! You have to enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($department) == '') {
echo '<div class="error_message">Attention! Please enter a department.</div>';
exit();
} else if(trim($preferphone) == '') {
echo '<div class="error_message">Attention! Please enter a preferred phone number.</div>';
exit();
} else if(!isPhone($preferphone)) {
echo '<div class="error_message">Attention! Please enter the right format for phone.</div>';
exit();
} else if(trim($website) == '') {
echo '<div class="error_message">Attention! Please enter a website name.</div>';
exit();
}
if($error == '') {
$secondarycontact = NULL;
$secondaryemail = 'random text';
$optionalphone = 'random text';
$address = "example#yahoo.com";
$clientaddress = $primaryemail;
//admin subject
$e_subject = $primarycontact .' has successfully been registered in the database';
//client subject
$c_subject = 'You have successfully been registered in the database';
/* another way of doing admin client email as array
$admin_email = array(
'e_body' => '$primarycontact has been registered in department '$department' \r\n\n',
'e_content' => 'You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n';
'e_reply' => 'You can contact $primarycontact via email, $primaryemail';
);*/
//admin email
$e_body = "$primarycontact has been registered in department '$department' \r\n\n";
//$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
//$e_content = "\"anything can be displayed here such as all the customers entered info\"\r\n\n";
$e_reply = "You can contact $primarycontact via email, $primaryemail ";
//client email
$c_body = "You has been registered in department '$department' \r\n\n";
$c_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
$c_reply = "For anymore information feel free to contact the administrator vis email, $address";
//admin msg
$msg = $e_body . $e_content . $e_reply;
//client msg
$cmsg = $c_body . $c_content . $c_reply;
//inserts information
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$preferphone."', '".$secondarycontact."', '".$secondaryemail."', '".$optionalphone."', '".$department."', '".$website."')");
if(mail($address, $e_subject, $msg, "From: $primaryemail\r\nReply-To: $primaryemail\r\nReturn-Path: $primaryemail\r\n")) {
//if mail was sent to admin then send to person who signed up
mail($primaryemail, $c_subject, $cmsg, "From: $address\r\nReply-To: $address\r\nReturn-Path: $address\r\n");
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo $secondarycontact. '<br />';
echo $secondaryemail. '<br />';
echo $optionalphone. '<br />';
//echo "<h1>User $primarycontact Successfully added onto '$department'.</h1>";
echo "<p>Thank you <strong>$primarycontact</strong>, your registration info has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
//all functions go here
//protects database from SQL injection
function protect($value) {
if(get_magic_quotes_gpc()){
return mysql_real_escape_string(stripslashes($value));
}else{
return mysql_real_escape_string($value);
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
function isPhone($number) {
return(preg_match("/^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/",$number));
}
?>
optionalphone,secondaryemail and secondarycontact are the only values that can be null
This will not work:
$foo = null;
mysql_query("INSERT INTO ... VALUES (".$foo.")");
This will:
mysql_query("INSERT INTO ... VALUES (NULL)");
So you might want to do it this way:
function quoted_string_or_null($var) {
return $var === null ? 'NULL' : "'".$var."'";
}
$foo = null;
mysql_query("INSERT INTO ... VALUES (".quoted_string_or_null($foo).")");
However, there is another problem: there is no way you will be getting real null values from your protect function or from $_POST. So you have to decide if an empty string is a legal value, or if empty strings should be converted to null. It's probably the latter, so you can make a small change and work with this:
function quoted_string_or_null($var) {
return ($var === null || $var === '') ? 'NULL' : "'".$var."'";
}
Rather than manually quoting the strings, use something to do this for you. See http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments is a function written for your issue:
<?php
function db_escape($values, $quotes = true) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$values[$key] = db_escape($value, $quotes);
}
}
else if ($values === null) {
$values = 'NULL';
}
else if (is_bool($values)) {
$values = $values ? 1 : 0;
}
else if (!is_numeric($values)) {
$values = mysql_real_escape_string($values);
if ($quotes) {
$values = '"' . $values . '"';
}
}
return $values;
}
?>
Once you have escaped each value, pass it without any extra quotes to the insert command.

Categories