PHP Mail Function

I've got a PHP mail function but no mail is being sent.

<?php
include ('common_includes.php');
//include ('include/common.inc');
include ('class/class.user.inc');
include ('class/class.city.inc');
include ('class/formvalidator.php');
//check user session first
/*if(isset($_SESSION['session_user_id']) && $_SESSION['session_user_id'])
{
	$userURL = $baseUrl."eng-profile.php";
	redirect($userURL);
	exit;
}	*/
//create user class object
$objCity 	= new Class_City();
$StateCODE = array();
$StateNAME = array();
$stateRes = $objCity->selectState();
while($stateRow = mysql_fetch_array($stateRes))
{
	$StateCODE[] = $stateRow['statecode'];
	$StateNAME[] = $stateRow['state'];
}
$smarty->assign("StateCODE",$StateCODE);
$smarty->assign("StateNAME",$StateNAME);


$objUser 	= new Class_User();



if(isset($_SESSION['session_user_id']) && $_SESSION['session_user_id']!="")
{
	$member_id = trim($_SESSION['session_user_id']);
	if($member_id!='')
	{
		
		$objUser->id = $member_id;
		$userRes = $objUser->selectUser();
		$userRow = mysql_fetch_array($userRes);
		
		$smarty->assign('name',$userRow["full_name"]);
		$smarty->assign('display_name',$userRow["display_name"]);
		$smarty->assign('rs_code',$userRow["RS_CODE"]);
		$smarty->assign('PAMA_Member_Number',$userRow["PAMA_Member_Number"]);
		$smarty->assign('shops_category',explode(", ",$userRow["shops_category"]));
		$smarty->assign('website_link',$userRow["website_link"]);
		$smarty->assign('email',$userRow["email"]);
		$smarty->assign('address',$userRow["address"]);
		$smarty->assign('city',$userRow["city"]);
		$smarty->assign('image',$userRow["image"]);
		$smarty->assign('state',$userRow["state"]);
		$smarty->assign('image',$userRow["image"]);
		$smarty->assign('zipcode',$userRow["zipcode"]);
		$smarty->assign('company',$userRow["COMPANY"]);
		$smarty->assign('phone',preg_replace('/[^0-9\.]/Uis', '',$userRow["phone"]));
		$smarty->assign('specialized',explode(", ",$userRow['specialized']));
		$smarty->assign('aircraft',$userRow["other_aircraft"]);
		$smarty->assign('website_link',$userRow["website_link"]);
		$smarty->assign('experiance',$userRow["experiance"]);
		$smarty->assign('about',$userRow["about"]);
		$smarty->assign('radius',$userRow["radius"]);
		//set update message
		
		$update_msg = "Page information has been updated successfully!";
	}
	else
	{
		$update_msg = "Page has been added successfully!";
		
	}
}
//create mail class object
$objMail 	= new Class_Mail();

// Creating object of SendEmailClass
$emailObj 	= new SendEmailClass;

//Form validator class object
$validator = new FormValidator();

/*//set default values
$user = array();
$user['name'] = "Name";
$user['address'] = "Address";
$user['phone'] = "Phone No";
$user['email'] = "Email Address";
$user['password'] = "";
$user['repassword'] = "";
$user['address'] = "Address";
$user['specialization'] = "Spacialization";
$user['website_link'] = "Website Link";
$user['experience'] = "Experience";
$user['about'] = "About";
$smarty->assign("user", $user);*/
		
//submit registration form

if($_SERVER['REQUEST_METHOD']=='POST')
{	
	//print_r($_POST);
	
	//if($_FILES['image']['size']>0 && $_FILES['image']['size']<5000 && ($_FILES['image']['type'] == 'image/jpeg' || $_FILES['image']['type'] == 'image/png' || $_FILES['image']['type'] == 'image/gif')){
	if(isset($_FILES['image']) && $_FILES['image']['size'] >0){
				define ("MAX_SIZE","10000");
				function getExtension($str) {

         $i = strrpos($str,".");
         if (!$i) { return ""; } 
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
				$image =$_FILES["image"]["name"];
				$uploadedfile = $_FILES['image']['tmp_name'];
				$name = uniqid().$image;
				
				if ($image){
					$filename = stripslashes($_FILES['image']['name']);
					$extension = getExtension($filename);
					$extension = strtolower($extension);
			
					if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")){
						$errors =  'Unknown Image extension';
					}else{
						$size=filesize($_FILES['thumb']['image']);
						if ($size > MAX_SIZE*1024){
							$errors="You have exceeded the size limit";
						}else{
							if($extension=="jpg" || $extension=="jpeg" ){
								$uploadedfile = $_FILES['image']['tmp_name'];
								$src = imagecreatefromjpeg($uploadedfile);
							}else if($extension=="png"){
								$uploadedfile = $_FILES['image']['tmp_name'];
								$src = imagecreatefrompng($uploadedfile);
							}else{
								$src = imagecreatefromgif($uploadedfile);
							}
							list($width,$height)=getimagesize($uploadedfile);
					
							if($height > 150){
								$newheight=150;
								$newwidth=($width/$height)*$newheight;
								if($newwidth > 150){$newwidth=150;}
							}else if($width > 150){
								$newwidth=150;
								$newheight=($height/$width)*$newwidth;
								if($newheight > 150){$newheight = 150;}
							}else{
								$newheight= $height;
								$newwidthL = $width;	
							}
						
							$tmp=imagecreatetruecolor($newwidth,$newheight);
							imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
				
							$target_path = "images/img/". $name;
							imagejpeg($tmp,$target_path,80);
							
							
							imagedestroy($src);
							imagedestroy($tmp);
						}
					}
				}
	}
	$_POST['shops_category'] = implode(", ",$_POST['shops_category']);
	$_POST['specialized'] = implode(", ",$_POST['specialized']);
	
    extract($_POST);
	$error_msg = "";
	$input_error_msg = "";
	
	$validator->addValidation("name","req","Name can not be left blank.");
	if($shops_category == '')
		$validator->addValidation("shops_category","req","Please select atleast one shop type");
		
	$validator->addValidation("name","alpha_s","Please enter only alphabetic character for name."); 
	
	$validator->addValidation("email","req","Email can not be left blank.");
	$validator->addValidation("email","email","Please provide valid email address.");
	//$validator->addValidation("image","req","Please provide valid image format as .jpeg, .png, .gif.");
	$validator->addValidation("address","req","Address can not be left blank.");
	$validator->addValidation("company","req","Company Name can not be left blank.");
	$validator->addValidation("city","req","City can not be left blank.");
	$validator->addValidation("state","req","State can not be left blank.");
	$validator->addValidation("zipcode","req","ZIPCODE can not be left blank.");
	$validator->addValidation("website_link","req","Website link can not be left blank.");
	if($specialized == '' && $aircraft == '')
		$validator->addValidation("specialized","req","Please select atleast one Aircraft");
		
	if(!isset($_SESSION["session_user_id"]) && $_SESSION["session_user_id"]=="")
	{
		$validator->addValidation("password","minlen=6","Password should be minimum 6 characters long.");
		$validator->addValidation("password","req","Password can not be left blank.");
		$validator->addValidation("repassword","eqelmnt=password","Confirm password should be same as password.");
		$validator->addValidation("repassword","req","Confirm password can not be left blank.");   
	}



	if(!$validator->ValidateForm())
	{
		$error_hash = $validator->GetErrors();
		$error_msg = "<strong>Please fix following errors.</strong>";
		$input_error_msg ="";
		foreach($error_hash as $inpname => $inp_err)
		{
			$input_error_msg .="<div class='error-masg-cont'>$inp_err</div>";
		}
	}

	//if no input validation erors occured
	if($input_error_msg=="")
	{
		
		$objUser->username   		= rteSafe($username);
		$objUser->display_name   	= rteSafe($contactname);
		$objUser->rscode   			= rteSafe($rscode);
		$objUser->PAMA_Member_Number   			= rteSafe($PAMA_Member_Number);
		$objUser->company   		= rteSafe($company);
		$objUser->shops_category	= rteSafe($shops_category);
		if(isset($password) && $password != ''){
		$objUser->password  		= md5(rteSafe($password));
		}
		$objUser->email  			= rteSafe($email);
		$objUser->full_name  		= rteSafe($name);
		$objUser->address  			= rteSafe($address);
		$objUser->city  			= rteSafe($city);
		$objUser->state  			= rteSafe($state);
		$objUser->zipcode			= rteSafe($zipcode);
		$objUser->phone  			= rteSafe(preg_replace('/[^0-9\.]/Uis', '',$phone));
		$objUser->specialized 		= rteSafe($specialized);
		$objUser->aircraft 			= rteSafe($aircraft);
		if($_FILES['image']['size'] >0)
		$objUser->image 			= rteSafe($target_path);
		$objUser->website_link 		= rteSafe($website_link);
		$objUser->experiance 		= rteSafe($experiance);
		$objUser->about 			= rteSafe($about);
		$objUser->radius 			= rteSafe($radius);
		$objUser->user_type  		= 2; 
		$objUser->status			= 1;
		
		
	
		//check existing email
	if(!isset($_SESSION["session_user_id"]) && $_SESSION["session_user_id"]=="")
	{
		if($objUser->validateExisringEmail())
		{
			$error_msg = "Provided email address already in use...!";
		}
	}
	}

	//if no errors found Inser in to database
	if($error_msg=="")
	{
	
		if(!isset($_SESSION["session_user_id"]) || $_SESSION["session_user_id"]=="")
		{
			$objDBReturn = $objUser->insertUpdateUser();
			/*print_r($objDBReturn);*/
			$user_id = $objDBReturn->nIdentity;
		
				//set POST variables
			/*	$url = 'http://phpserver/airrepair/paypal/pay.php';
				//$url = 'http://www.freedomonweb.com/demo/airrepair/paypal/pay.php';
				$fields = array(
							'user_id'=>urlencode($user_id),
							'amount'=>urlencode('49.95'),
							'type'=>urlencode('mechanic_bid'),
							'user_type'=>urlencode('mechanic')
						);
				
				//url-ify the data for the POST
				foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
				rtrim($fields_string,'&');
				
				//open connection
				$ch = curl_init();
				//echo $ch;
				//set the url, number of POST vars, POST data
				curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
				curl_setopt($ch, CURLOPT_FAILONERROR, 1);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
				curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
				curl_setopt($ch, CURLOPT_TIMEOUT, 0); // times out after Ns
				curl_setopt($ch, CURLOPT_POST, 1); // set POST method
				curl_setopt($ch, CURLOPT_POSTFIELDS, "FREE_TEXT=php&op=1013&rel_code=1102"); // add POST fields
				
				curl_setopt($ch, CURLOPT_FAILONERROR, 0);
				curl_setopt($ch, CURLOPT_VERBOSE, 1);
				curl_setopt($ch, CURLOPT_HEADER, 1);
				curl_setopt($ch, CURLOPT_COOKIEFILE, 1);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
				curl_setopt($ch,CURLOPT_POST,count($fields));
				curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
				
				//execute post
				$result = curl_exec($ch);
				
				//close connection
				curl_close($ch);
				echo $result;*/
				$_SESSION['session_user_id'] 		= $user_id;
			
		$_SESSION['session_user_name']		= $objUser->username ;
		$_SESSION['session_user_type'] 		= $objUser->user_type;
		$_SESSION['session_last_login']		= date('D jS M Y h:i A', strtotime($last_login));  //Mon 8th Aug 2009 03:12 PM
		
		//log user login dates to DB table
		$objUser->user_id = $user_id;
		$objUser->loggedUserLoginDates();
					header("location:subscription.php?id=".$user_id);
				 
		}
		else if(isset($_SESSION["session_user_id"]) && $_SESSION["session_user_id"]!="")
		{
			$objUser->id = $_SESSION["session_user_id"];
			$objDBReturn = $objUser->insertUpdateUser();
			redirect("eng-profile.php");
		}
		
		/*redirect("thanks.php?type=regconfirm");*/
		
		if($objDBReturn->nIdentity && $objDBReturn->nErrorCode==0)
		{
			//echo "Hi";
			//create encrypted activation link
			//$encCode = "username=".$email."&id=".$objDBReturn->nIdentity;
			$encCode = "username=Airrepair&id=".$objDBReturn->nIdentity;
			$activation_link = $baseUrl."activate.php?".$objEnc->encrypt($encCode);
			
			//get email template
			$objMail->mail_title	= "Email Template"; 
			$MailTemplate			= $objMail->selectMailTemplate();
			$templateRowArr 		= mysql_fetch_array($MailTemplate);
			$mail_content			= $templateRowArr['mail_content'];
			$mail_content			= str_replace("#link#",$baseUrl,$mail_content);
				
			//get registration email content
			$objMail->mail_title	= "RepairAPlane.com Machanic Registration"; 
			$MailRes 				= $objMail->selectMailTemplate();
			$mailRowArr 			= mysql_fetch_array($MailRes);
			$subject 				= $mailRowArr['mail_subject'];  
			$message_content		= $mailRowArr['mail_content'];
			
			//replace message content with mail template message content variable
			$mail_content			= str_replace("#message_content#",$message_content,$mail_content);
			$mail_content			= str_replace("#link#",$baseUrl,$mail_content);

			//send registration email to user
			//$name = ucfirst($first_name).' '.ucfirst($last_name);
			//$mail_content = str_replace("#name#", $name, $mail_content);
			$mail_content = str_replace("#name#", $full_name, $mail_content);
			
			//$mail_content = str_replace("#username#", $username, $mail_content);
			$mail_content = str_replace("#username#", $email, $mail_content);
			$mail_content = str_replace("#password#", $password, $mail_content);
			$mail_content = str_replace("#activation_link#", $activation_link, $mail_content);
			
			$emailStatus = $emailObj->SendHtmlMail($email, $subject, $mail_content, $mailFrom);
			//echo $mail_content;
			
			if($emailStatus)
			{
				success_msg("Thank you for registering with Air Repair Team, a confirmation email has been sent to your email address.");
				
				//send mail to admin
				$admin_Subject =" Machanic Registered at Air Repair";
				$admin_Message = "Hello Administrator,<br />A new Machanic user has registered at Air Repair.<br />This email contains user details:<br /><br />";
				$admin_Message .="<br /><b>Full Name:</b> ".$name;
				$admin_Message .="<br /><b>Email:</b> ".$email;
				$admin_Message .= "<br /><br />Please do not respond to this message as it is automatically generated and is for information purposes only.";
				$emailObj->SendHtmlMail($admin_email, $admin_Subject, $admin_Message, $mailFrom);
			}
			else
			{
				failure_msg("Error occured while sending email, please contact Administrator to confirm your registration");
			}
			//redirect("thanks.php?type=regconfirm");
		}
		//redirect("thanks.php?type=regconfirm");
	}//end of if
	
	
	//assign error messages
	$smarty->assign('error_msg',$error_msg);
	
	//Show post data
	$smarty->assign('display_name',$contactname);
	$smarty->assign('name',$name);
	$smarty->assign('rs_code',$rscode);
	$smarty->assign('PAMA_Member_Number',$PAMA_Member_Number);
	$smarty->assign('shops_category',explode(", ",$shops_category));
	$smarty->assign('email',$email);
	$smarty->assign('address',$address);
	$smarty->assign('city',$city);
	$smarty->assign('state',$state);
	$smarty->assign('zipcode',$zipcode);
	$smarty->assign('phone',$phone);
	$smarty->assign('specialized',explode(", ",$specialized));
	$smarty->assign('website_link',$website_link);
	$smarty->assign('experiance',$experiance);
	$smarty->assign('aircraft',$aircraft);
	$smarty->assign('about',$about);
	
	
	$smarty->assign('input_error_msg',$input_error_msg);

}

//assign variable and display template
$smarty->assign('site_page_title',SITE_HOME);
$smarty->assign('site_title',$site_title);

$smarty->display('machanic_registration.tpl');

?>

Open in new window

webdorkAsked:
Who is Participating?
 
akashsureshCommented:
PHP mail does not require SMTP authorization.You can directly give a from address and send.Some providers do block smtp authorization.
0
 
Julian HansenCommented:
Ok , you are going to need to put some debug messages in that code to see where it is failing.

There are a lot of if statements that could be where the problem is.

Put some
echo "Debug: line: " . __LINE__ ."<br/>";

Open in new window


Into the if's and create else's where they don't exist and add the line above.

Run the app again and take a look at the trace of messages (line numbers) that should tell you where it is failing. We can take it from there.
0
 
webdorkAuthor Commented:
Here is the SendMailClass.php file. I see that the return path is incorrect, some different domain. Do I need to just insert the correct domain?Here is the path to mail assigned by the hosting co.: /usr/sbin/sendmail

<?
// Calling SendHtmlMail function to send mail.
//ini_set('SMTP','mail.freedomonweb.com');
//ini_set('smtp_port',25);
        
class SendEmailClass
{
	var $emailId;
	var $subject;
	var $mailBody;
	var $from;
	var $headers;
	var $message;
	var $cc;
	var $bcc;
/*
 * simple Text mail format
 *  
 */
	function SendEmail($emailId, $subject, $mailBody, $from)
	{
		if (@mail($emailId, $subject, $mailBody, "From: $from\n"))
		{
			return true;
		}
		else
		{
			return false;
		}

	}
/*to send the email
 *  
 * 	in HTML format	
*/	
	function SendHtmlMail($emailId, $subject, $message, $from)
	{
		$headers="MIME-Version: 1.0\n" .
		"Content-Transfer-Encoding: 8bit\n" .
		"Content-type: text/html; charset='iso-8859-1'\n" .
	 	"Return-Path: <mail.freedomonweb.com>\n" .
		"From: ".$from."\n";
		if(isset($this->cc) && $this->cc!="")
		{
			$headers .= 'Cc: '.$this->cc . "\r\n";
		}
		if(isset($this->bcc) && $this->bcc!="")
		{
			$headers .= 'Bcc: '.$this->bcc . "\r\n";
		}	
		
		if (@mail($emailId, $subject, $message, $headers))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}
?>

Open in new window

0
 
webdorkAuthor Commented:
Not sure syntax in else statement:

I've commented out the redirect (line 6). I cant tell if that $objDBReturn is a nested conditional statement. Is there no end if declaration in PHP?

Where would I place the else stment?
What does this mean: if($objDBReturn->nIdentity && $objDBReturn->nErrorCode==0)


		else if(isset($_SESSION["session_user_id"]) && $_SESSION["session_user_id"]!="")
		{
			$objUser->id = $_SESSION["session_user_id"];
			$objDBReturn = $objUser->insertUpdateUser();
			//echo "Hi";
			//redirect("eng-profile.php");
		}
		
		/*redirect("thanks.php?type=regconfirm");*/
		
		if($objDBReturn->nIdentity && $objDBReturn->nErrorCode==0)
		{
			echo "Yes Mail";
			//create encrypted activation link
			//$encCode = "username=".$email."&id=".$objDBReturn->nIdentity;
			$encCode = "username=Airrepair&id=".$objDBReturn->nIdentity;
			$activation_link = $baseUrl."activate.php?".$objEnc->encrypt($encCode);
			
			//get email template
			$objMail->mail_title	= "Email Template"; 
			$MailTemplate			= $objMail->selectMailTemplate();
			$templateRowArr 		= mysql_fetch_array($MailTemplate);
			$mail_content			= $templateRowArr['mail_content'];
			$mail_content			= str_replace("#link#",$baseUrl,$mail_content);
				
			//get registration email content
			$objMail->mail_title	= "RepairAPlane.com Machanic Registration"; 
			$MailRes 				= $objMail->selectMailTemplate();
			$mailRowArr 			= mysql_fetch_array($MailRes);
			$subject 				= $mailRowArr['mail_subject'];  
			$message_content		= $mailRowArr['mail_content'];
			
			//replace message content with mail template message content variable
			$mail_content			= str_replace("#message_content#",$message_content,$mail_content);
			$mail_content			= str_replace("#link#",$baseUrl,$mail_content);

			//send registration email to user
			//$name = ucfirst($first_name).' '.ucfirst($last_name);
			//$mail_content = str_replace("#name#", $name, $mail_content);
			$mail_content = str_replace("#name#", $full_name, $mail_content);
			
			//$mail_content = str_replace("#username#", $username, $mail_content);
			$mail_content = str_replace("#username#", $email, $mail_content);
			$mail_content = str_replace("#password#", $password, $mail_content);
			$mail_content = str_replace("#activation_link#", $activation_link, $mail_content);
			
			$emailStatus = $emailObj->SendHtmlMail($email, $subject, $mail_content, $mailFrom);
			//echo $mail_content;
			
			
			if($emailStatus)
			{
				success_msg("Thank you for registering with Air Repair Team, a confirmation email has been sent to your email address.");
				
				//send mail to admin
				$admin_Subject =" Machanic Registered at Air Repair";
				$admin_Message = "Hello Administrator,<br />A new Machanic user has registered at Air Repair.<br />This email contains user details:<br /><br />";
				$admin_Message .="<br /><b>Full Name:</b> ".$name;
				$admin_Message .="<br /><b>Email:</b> ".$email;
				$admin_Message .= "<br /><br />Please do not respond to this message as it is automatically generated and is for information purposes only.";
				$emailObj->SendHtmlMail($admin_email, $admin_Subject, $admin_Message, $mailFrom);
			}
			else
			{
				failure_msg("Error occured while sending email, please contact Administrator to confirm your registration");
			}
			//redirect("thanks.php?type=regconfirm");
		}
		//redirect("thanks.php?type=regconfirm");
	}//end of if

Open in new window

0
 
Julian HansenCommented:
PHP does have an endif if you declare if statement like so

if (condition) :
...
endif;

Open in new window

In this case it is not using that so you would do this

else if(isset($_SESSION["session_user_id"]) && $_SESSION["session_user_id"]!="")
{
  $objUser->id = $_SESSION["session_user_id"];
  $objDBReturn = $objUser->insertUpdateUser();
  //echo "Hi";
  //redirect("eng-profile.php");
}
else {
  echo "DEBUG: Line : " . __LINE__ . "<br/>";
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.