PHPmailer body message error if no array passing

Hi, Im making a form that contain 1 set of radio button and 1 set of checkbox. If I check the radio button and check the checkbox, all is working fine. But if I check the radio button but dont check any checkbox, I still receive the email but they will be some error messages at the page.

This is the errors.

Im suspecting it’s because of the body setting on the phpmailer. Got any insight?
Below is the full code. Variable lenses is for the radio button and disposable_lenses is for the checkbox. Do tell me if all these code are hard to read, then I’ll edit show only some part of the code.

<?php
//index.php

$error = '';
$outlet = '';
$fullname = '';
$email = '';
$contact_no = '';
$lenses = '';
$disposable_lenses = '';
$date = '';
$time = '';

function clean_text($string)
{
	$string = trim($string);
	$string = stripslashes($string);
	$string = htmlspecialchars($string);
	return $string;
}

if(isset($_POST["submit"]))
{
	if(empty($_POST["outlet"]))
	{
		$error .= '<p><label class="text-danger">Outlet is required</label></p>';
	}
	else
	{
		$outlet = clean_text($_POST["outlet"]);
	}
	if(empty($_POST["fullname"]))
	{
		$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
	}
	else
	{
		$fullname = clean_text($_POST["fullname"]);
		if(!preg_match("/^[a-zA-Z ]*$/",$fullname))
		{
			$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
		}
	}
	if(empty($_POST["email"]))
	{
		$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
	}
	else
	{
		$email = clean_text($_POST["email"]);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		{
			$error .= '<p><label class="text-danger">Invalid email format</label></p>';
		}
	}
	if(empty($_POST["contact_no"]))
	{
		$error .= '<p><label class="text-danger">Contact Number is required</label></p>';
	}
	else
	{
		$contact_no = clean_text($_POST["contact_no"]);
	}
	if(empty($_POST["lenses"])) {
		$error .= '<p><label class="text-danger">Lenses is required</label></p>';
	}
	
	else {
		if($_POST["lenses"] == "Yes" && empty($_POST["disposable_lenses"])) {
			$error .= '<p><label class="text-danger">Disposable_lens is required</label></p>';
		}
		else{
			$disposable_lenses[] =  $_POST["disposable_lenses"];
		}   
	}
	
	if(!empty($_POST["disposable_lenses"])) {
		$disposablelens = implode(",",$disposable_lenses[0]);
	}
		if(empty($error)) {
			echo "Have you worn contact Lens before? ".$_POST["lenses"]."<br>";
			echo "If yes, which type of disposable contact lens have you worn before? ".$disposablelens;
		}
	if(empty($_POST["date"]))
	{
		$error .= '<p><label class="text-danger">Date is required</label></p>';
	}
	else
	{
		$date = clean_text($_POST["date"]);
	}
	if(empty($_POST["time"]))
	{
		$error .= '<p><label class="text-danger">Time is required</label></p>';
	}
	else
	{
		$time = clean_text($_POST["time"]);
	}

	if($error == '')
	{
		require 'class/class.phpmailer.php';
		$mail = new PHPMailer;
		$mail->IsSMTP();								//Sets Mailer to send message using SMTP
		$mail->Host = 'xxxxxx';			//Sets the SMTP hosts of your Email hosting, this for Godaddy
		$mail->Port = '26';								//Sets the default SMTP server port
		$mail->SMTPAuth = true;							//Sets SMTP authentication. Utilizes the Username and Password variables
		$mail->Username = 'xxxxxx';		//Sets SMTP username
		$mail->Password = 'xxxxxx';					//Sets SMTP password
		$mail->SMTPSecure = '';							//Sets connection prefix. Options are "", "ssl" or "tls"
		$mail->From = $_POST["email"];					//Sets the From email address for the message
		$mail->FromName = $_POST["fullname"];			//Sets the From name of the message
		$mail->AddAddress('nz_rink@yahoo.com', 'Nazrin');		//Adds a "To" address
		$mail->AddCC($_POST["email"], $_POST["fullname"]);	//Adds a "Cc" address
		$mail->WordWrap = 50;							//Sets word wrapping on the body of the message to a given number of characters
		$mail->IsHTML(true);			
		$mail->Subject = 'Eye Appointment';				//Sets the Subject of the message
		$mail->Body = join('', array(
			"Outlet: ",
			$_POST['outlet'],
			"<br/>",
			"Full Name: ",
			$_POST['fullname'],
			"<br/>",
			"Email Address: ",
			$_POST['email'],
			"<br/>",
			"Phone Number:",
			$_POST['contact_no'],
			"<br/>",
			"Have you worn contact lens before?: ",
			$_POST['lenses'],
			"<br/>",
			"If yes, which type of disposable contact lens have you worn before?: ",
			join(', ', $_POST['disposable_lenses']),
			"<br/>",
			"Appointment Date ",
			$_POST['date'],
			"<br/>",
			"Appointment Time ",
			$_POST['time']
			));											//An HTML or plain text message body
		if($mail->Send())								//Send an Email. Return true on success or false on error
		{
			$error = '<label class="text-success">Thank you for contacting us</label>';
		}
		else
		{
			$error = '<label class="text-danger">There is an Error</label>';
		}
		$outlet = '';
		$fullname = '';
		$email = '';
		$contact_no = '';
		$lenses = '';
		$disposable_lenses = '';
		$date = '';
		$time = '';
	}
}

?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<style>
#map-canvas {

	height:368px;
}

#myDIV { display:none; }
</style>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<script src="https://maps.googleapis.com/maps/api/js"></script>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

		<title>Eyes Appointment</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
		<script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js"></script>



<script>
	var map;

	var markerData= [
		{lat: 3.173605 , lng: 101.681340  , zoom: 18 , name: "Outlet 1"},
		{lat: 3.003307 , lng: 101.541344  , zoom: 18 , name: "Outlet 2"},
		{lat: 3.062388 , lng: 101.670633  , zoom: 18 , name: "Outlet 3"},
	];
	 
	function initialize() {
		 	map = new google.maps.Map(document.getElementById('map-canvas'), {
				zoom: 18,
				center: {lat: 3.173605, lng: 101.681340}
			});
			markerData.forEach(function(data) {
				var newmarker= new google.maps.Marker({
					map:map,
					position:{lat:data.lat, lng:data.lng},
					title: data.name
				});
				jQuery("#selectlocation").append('<option value="'+[data.lat, data.lng, data.zoom, data.name].join(' | ')+'">'+data.name+'</option>');
			});

	}

	google.maps.event.addDomListener(window, 'load', initialize);

	jQuery(document).on('change','#selectlocation',function() {
		var latlngzoom = jQuery(this).val().split('|');
		var newzoom = 1*latlngzoom[2],
		newlat = 1*latlngzoom[0],
		newlng = 1*latlngzoom[1];
		map.setZoom(newzoom);
		map.setCenter({lat:newlat, lng:newlng});
	});

</script>

<script>
function show() {	
    var x = document.getElementById("myDIV");    
        x.style.display = "block";   
}

function hide(){
 var x = document.getElementById("myDIV");    
        x.style.display = "none";   
}
</script>
</head>
<body>



<br />
		<div class="container">
			<div class="row">
				<div class="col-md-8" style="margin:0 auto; float:none;">
					<h3 align="center">Eyes Appointment</h3>
					<br />
					<?php echo $error; ?>
					<form action="" method="post">


> 						<div class="form-group" id="map-canvas"></div>
						<!-- <div class="form-group">
							<select name="outlet" class="form-control" value="<?php echo $outlet; ?>">
							<option>Outlet 1</option>
							<option>Outlet 2</option>
							<option>Outlet 3</option>
							<option>Outlet 4</option>
							<option>Outlet 5</option>
							</select>
						</div> -->
						<div class="form-group">
							<select id="selectlocation" name="outlet"  class="form-control" value="<?php echo $outlet; ?>">
								<option value="3.173605|101.681340|18" disabled selected>Please select</option>
							</select>
						</div>

						<div class="form-group">
							<input type="text" name="fullname" placeholder="Full Name" class="form-control" value="<?php echo $fullname; ? />
						</div>
						<div class="form-group">
 							<input type="text" name="email" class="form-control" placeholder="Email address" value="<?php echo $email; ?>" />
						</div>
						<div class="form-group">
							<input type="text" name="contact_no" class="form-control" placeholder="Contact (0XX XXX XXXX)" value="<?php echo $contact_no; ?>" />
						</div>
						<div class="form-group">
						<p>Have you worn contact Lens before?</p>
							<input onclick="show()" type="radio" name="lenses"  value="Yes"/> Yes<br>
        					<input onclick="hide()"type="radio" name="lenses"  value="No"/> No<br>
						</div>
						<div class="form-group" id="myDIV">
							<p>If yes, which type of disposable contact lens have you worn before?</p>
							<input type="checkbox" name="disposable_lenses[]"  value="Monthly"/> Monthly<br>
  							<input type="checkbox" name="disposable_lenses[]"  value="Daily Disposables"/> Daily Disposables<br>
						</div>
						<div class="form-group">
							<input type="text" name="date"  alt="date" class="IP_calendar" title="d/m/Y" placeholder="Appointment Date"/>
						</div>
						<div class="form-group">
							<select name="time" class="form-control" value="<?php echo $time; ?>">
							<option value="" disabled selected>Please select</option>
							<option>10:00am</option>
							<option>1:00pm</option>
							<option>3:00pm</option>
							<option>5:00pm</option>
							<option>7:00pm</option>
							</select>
						</div>
						<div class="form-group" align="center">
							<input type="submit" name="submit" value="Submit" class="btn btn-info" />
						</div>
					</form>
				</div>
			</div>
		</div>
</body>
</html>

Well if I may suggest, instead of attempting to modify the join() array simply build the message as a string where you can easily add IF conditions to control the message. Something like this.

$message = "Outlet: " . $_POST['outlet'].
			"<br/>Full Name: " . $_POST['fullname'].
			"<br/>Email Address: " . $_POST['email'].
			"<br/>Phone Number: " . $_POST['contact_no'];
		if(!empty($_POST['lenses'])):	
			$message .= "<br/>Have you worn contact lens before?: " . $_POST['lenses'];
		endif;
		if(!empty($_POST['disposable_lenses'])):	
			$message .= "<br/>If yes, which type of disposable contact lens have you worn before?: " . $_POST['disposable_lenses'];
		endif;
		$message .= "<br/>Appointment Date " . $_POST['date'].
			"<br/>Appointment Time " . $_POST['time']; 
			
			
		require 'class/class.phpmailer.php';
		$mail = new PHPMailer;
		$mail->IsSMTP();								//Sets Mailer to send message using SMTP
		$mail->Host = 'xxxxxx';			//Sets the SMTP hosts of your Email hosting, this for Godaddy
		$mail->Port = '26';								//Sets the default SMTP server port
		$mail->SMTPAuth = true;							//Sets SMTP authentication. Utilizes the Username and Password variables
		$mail->Username = 'xxxxxx';		//Sets SMTP username
		$mail->Password = 'xxxxxx';					//Sets SMTP password
		$mail->SMTPSecure = '';							//Sets connection prefix. Options are "", "ssl" or "tls"
		$mail->From = $_POST["email"];					//Sets the From email address for the message
		$mail->FromName = $_POST["fullname"];			//Sets the From name of the message
		$mail->AddAddress('nz_rink@yahoo.com', 'Nazrin');		//Adds a "To" address
		$mail->AddCC($_POST["email"], $_POST["fullname"]);	//Adds a "Cc" address
		$mail->WordWrap = 50;							//Sets word wrapping on the body of the message to a given number of characters
		$mail->IsHTML(true);			
		$mail->Subject = 'Eye Appointment';				//Sets the Subject of the message
		$mail->Body = $message;			

You use form variables without checking whether or not they exist. When your browser submits the form, if the checkbox does not have any value in it, then it will not be submitted. So you must check whether it exists before you try to use it, which is what @Drummin is doing with the if (!empty()) construction, and what you are doing earlier on to check whether or not the user filled out the form correctly. You just need to extend that to the mail sending or, indeed, any other use of the optional form variables.

Of course, if you then go on to extend the script so that it stores the user input in a database table (for example, in case the email does not send for some reason, you still have the data), you will need to validate those user inputs before storing them.

I’d also suggest that you use something other than the form-fillers email address as the “from” address. There’s a reasonable chance your mail server won’t allow you to send emails from anything other than your own configured domain, as allowing it would be effectively an open relay.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.