Jump to content

Secure Email


siri

Recommended Posts

Can anyone explain what exactly the function eregi("to:",$field) || eregi("cc:",$field) does in the following code:<?phpfunction spamcheck($field) {//eregi() performs a case insensitive regular expression match if(eregi("to:",$field) || eregi("cc:",$field)) { return TRUE; } else { return FALSE; } }//if "email" is filled out, send emailif (isset($_REQUEST['email'])) { //check if the email address is invalid $mailcheck = spamcheck($_REQUEST['email']); if ($mailcheck==TRUE) { echo "Invalid input"; } else { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "Subject: $subject", $message, "From: $email" ); echo "Thank you for using our mail form"; } }else//if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'> Email: <input name='email' type='text' /><br /> Subject: <input name='subject' type='text' /><br /> Message:<br /> <textarea name='message' rows='15' cols='40'> </textarea><br /> <input type='submit' /> </form>"; }?>

Link to comment
Share on other sites

Not quite sure, but i think it stops people injecting code and making the form send out loads of emails.PS. Is that the code from the Secure Email example here?

Link to comment
Share on other sites

My problem with the original example, the one in the tutorial and description. Is what is the "mailform.php" reference to, meaning.1) Is it and external php page that my page references for scripting, and if so what is on that "mailform.php" page.2) Is it the title of my page, which if I read the note, says

/if "email" is not filled out, display the form { echo "<form method='post' action='mailform.php'>
does this reload my page "mailform.php" encouraging people to check the information they enter of complete it if it is not done so.I'll tell you, I copied that entire sample of code into a new page, which I saved as "sendmail.php". When I ran it I notice 2 things, both time I ran it, once with fields all full, and once with errors in the "from" field, I got and error message saying mailform.php could not be found. Which by the comments in the code, the mailform.php should only be called when the email is not fill out.Second scenario I changed the "mailform.php" to "sendmail.php", the title of my page and well, with all the fields filled out it send the email off not problem, half the field filled out it sent it no problem, no fields filled out it sent it no problem. Something tells me that really did not work.If someone can clarify the code and or what i am doing wrong i would appreciate it.Thanks
Link to comment
Share on other sites

Something tells me that really did not work.
What did not work?And if you know what if() is, if you know what $_REQUEST[] is, if you know what isset() is, if you know what the form action is, and you can easily follow the code.
Link to comment
Share on other sites

My problem with the original example, the one in the tutorial and description. Is what is the "mailform.php" reference to, meaning.1) Is it and external php page that my page references for scripting, and if so what is on that "mailform.php" page.2) Is it the title of my page, which if I read the note, says
In this code: <form action="mailform.php" method="post">The file in the action attribute is where the user gets sent, and the form information gets submitted, when the user presses the Submit button. So, when the user submits the form, all of the information they put in the form goes to the mailform.php page to be processed. You are supposed to write the mailform.php page. If you don't want to call it mailform.php, then name it whatever you want. The processing page should access the submitted information using the $_POST variable and do whatever you want it to do, in this case probably verify that required information was given, maybe check that an email address is the proper format, and then send an email. It's also fine if the form itself and the form processor are on the same page. The mailform.php page can check to see if the form was submitted, if not display the form, and if it was send the email. If the form was submitted but there were problems, then it displays the form again with the information that was submitted filled in automatically.
Link to comment
Share on other sites

justsomeguy:Thanks a lot, I really appreciate it. I will look into it some more. If you are up to it maybe you could give me a sample of what would be in the "mailform.php", what it might look like. If not, no problem, thanks again.skym:What is with the bloody attitude, I have no problem reading code, if you had read my post, I asked about the "mailform.php". I had no problem with the logic of the statement. As it is stated in the argument

/if "email" is not filled out, display the form{echo "<form method='post' action='mailform.php'>
Like I said, I did not fill out individual fields, or even the whole form, but it stilled sent the e-mail any ways. And that is what I meant when I said
Something tells me that really did not work.
Because it shouldn't have sent it, no.You see 1 post and think I don't know what way is up, a little bit about myself I have been doing Flash AS for years, thank you very much. And another thing, if I fully understood php I would not be looking at the tutorial of this site and posting on this forum for that matter. But thanks anyways...for nothing.
Link to comment
Share on other sites

  • 2 months later...

If anyone is wondering like I was on how to secure your e-mail form page here is what I put together from different sources and with a little of my own flair. If you had questions on the code found on this thread or on the w3school secure email, I will try to explain that as well.The code should actually be broken up. The processing code and the form code do not need to be together at all. One thing you need to think of, is how do I notify the user that they made a mistake, or forgot some information. I do this by redirecting the user back to the email_form.php page using the "header (Location...) command with a flag variable that correspond to the error generated. Then the error is displayed above the form.So the two very basic pages would look something like this:email_form.php

// Process Error message on failed submission	$flg = "";	$error = "";		if (isset($HTTP_GET_VARS["flg"])){		$flg = $HTTP_GET_VARS["flg"];	}		switch ($flg) {		case "yellow":			$error = "That Email Address already exists in our Database.<br>Please Select Another.<br />";			break;		case "red":			$error = "You messed up";			break;		case "blue":			$error = "You forgot to place and e-mail address.";			break;		case "pink":			$error = "Please add a valid email address";			break;		case "black":			$error = "You seem to have some code we do not recognize.";			break;		case "white":			$error = "The security code you entered did not match.";			break;		default:			$error = "";	}?>?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sending an Email</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><table>	<tr>		<td>			<?php				if ($error != ""){					echo ('<table id="etable"><tr><td height="50" id="eerror">');					echo ($error);				} else {					echo ('<table><tr><td  height="56px">');				}			?>								</td>				</tr>			</table>		</td>	</tr>	<tr>	<td>		<form name="email_form" method="post" action="./process_email.php">		<table cellspacing="3" cellpadding="1">			<tr>				<td>					First Name:				</td>				<td >					<input name="fname" type="text" value="<?php echo ( $sFName );?>" size="25" maxlength="60" />				</td>			</tr>			<tr>				<td>					Last Name:				</td>				<td>					<input name="lname" type="text"  value="<?php  echo ( $sLName ); ?>" size="25" maxlength="60" /><br/>				</td>			<tr>					<td>					Company:				</td>				<td>					<input name="company_name" type="text" value="<?php  echo ( $sCompany ); ?>" size="25" maxlength="75" /><br/>				</td>							</tr>				<tr>				<td>					Phone Number:				</td>				<td>					<input name="phone" type="text"  value="<?php  echo ( $sPhone ); ?>" size="15" maxlength="12" />				</td>			</tr>				<tr>					<td>					E-mail:				</td>				<td>					<input name="email" type="text" id="subject" value="<?php  echo ( $sEmail ); ?>" size="56" maxlength="50" /><br/>				</td>			</tr>				 			<tr>					<td>					Subject:				</td>				<td>					<input name="subject" type="text" id="subject" value="<?php  echo ( $sSubject ); ?>" size="56" maxlength="80" /><br/>				</td>			</tr>			<tr>					<td id="etd" colspan="2">					Message:				</td>			</tr>				<tr>				<td id="efield" colspan="2">					<textarea name="msg" cols="42" rows="10" id="textarea2"><?php  echo ( $sMsg ); ?></textarea>  				</td>			</tr>			<tr>					<td colspan="2">							<INPUT TYPE="hidden" NAME="RequestId" VALUE="<?php echo($request_id)?>">					</FORM>				</td>			</tr>			<tr>				<td>					<INPUT TYPE="submit" VALUE="Submit E-mail">				</td>			</tr>		</table>			</FORM>	</td></tr></table></body></html>

process_email.php

<?php		$fname = $_REQUEST["fname"];	$lname = $_REQUEST["lname"];	$email = $_REQUEST["email"];	$subject = $_REQUEST["subject"]; 	$company_name = $_REQUEST["company_name"];	$phone = $_REQUEST["phone"];	$msg = $_REQUEST["msg"];		function spamcheck($field) {	  //eregi() performs a case insensitive regular expression match	  if(eregi("to:",$field) || eregi("cc:",$field)) {		return TRUE;	} else {		return FALSE;	}  }//if "email" is filled out, send email,	if (isset($email)) {	  //check to see if the email address is invalid because is has extra code.	  $mailcheck = spamcheck($email);	  if ($mailcheck==TRUE){			// If it does have questionable code, like To; or Cc:, do this,			header ("Location: ./email_form.php?flag=red");		  break;	  } else { 		//  If not, send the email.   		mail("somebody@some_domain.com", "Subject: ".$subject, $message, "From: ".$email );	}  } else {		//if "email" is not filled out, display the form	  header ("Location: ./email_form.php?flag=red");	  break;	}	?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Processing e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><!-- Your message to display that the message went through. --><p>Thank you <?php echo ($fname." ".$lname); ?> for the e-mail. It has been sent off to the appropriate people.</body></html>

That is it in a nut shell. If you want a little more robust processing pages, use the same email_form.php page, but use this code for for your process_email.php page. Take note that any code used from this point forward you need to use sessions cookie. To make sure is it initiated, in a folder named include, place a file named session_init.php. In that file you should have <?php $_SESSION['SESSION'] = TRUE; ?> if nothing else.Some other useful things to have are:

<?php	$_SESSION['APP_MX'] = "mail.somedomain.com";	$_SESSION['APP_SERVER'] = "somedomain.com";	$_SESSION['SITE_EMAIL'] = "someone@somedomain.com";  // Where the e-mails should be sent to.		$_SESSION['MYSQL_SERVER'] = "localhost";	$_SESSION['MYSQL_LOGIN'] = "<username>"; // The one used to login into your Database.	$_SESSION['MYSQL_PASS'] = "<password>";  // The one used to login into your Database.	$_SESSION['MYSQL_DB'] = "";		$_SESSION['LOGGEDIN'] = "";	$_SESSION['USERID'] = 0;		$_SESSION['E_MAIL'] = "";	$_SESSION['F_NAME'] = "";	$_SESSION['L_NAME'] = "";			$_SESSION['SESSION'] = TRUE;	?>

process_email.php

<?php	session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");	$_SESSION['F_NAME'] = $_REQUEST["fname"];	$_SESSION['L_NAME'] = $_REQUEST["lname"];	$_SESSION['E_MAIL'] = $_REQUEST["email"];	$_SESSION['S_SUBJECT'] = $_REQUEST["subject"]; 	$_SESSION['S_COMPANY'] = $_REQUEST["company_name"];	$_SESSION['S_PHONE'] = $_REQUEST["phone"];	$_SESSION['S_MESSAGE'] = $_REQUEST["msg"];		function spamcheck($field) {		  // eregi() performs a case insensitive regular expression match		  if(eregi("to:",$field) || eregi("cc:",$field)) {				return TRUE;			} else {				return FALSE;			}	  }	// Validates according to the RFC 822 rules. (http://www.faqs.org/rfcs/rfc822.html)	function is_valid_email_address($e_mail){			$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';			$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';			$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';			$quoted_pair = '\\x5c[\\x00-\\x7f]';			$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";			$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";			$domain_ref = $atom;			$sub_domain = "($domain_ref|$domain_literal)";			$word = "($atom|$quoted_string)";			$domain = "$sub_domain(\\x2e$sub_domain)*";			$local_part = "$word(\\x2e$word)*";			$addr_spec = "$local_part\\x40$domain";			return preg_match("!^$addr_spec$!", $e_mail) ? 1 : 0;	}	//if "email" is filled out, proceed...	if (isset($_SESSION['E_MAIL'])){	  //check to see if the email address has spoofing code added.	  $mailcheck = spamcheck($email);	  // If it does, send it back to the form with a warning/		if ($mailcheck==TRUE){			$_SESSION['E_MAIL'] = ""; //Reset the email address just in case.		header ("Location: ./contact_us.php?flg=black");		  break;	  } else { 		// If it does not have questionable code, check to see if the email address is valid.			if (is_valid_email_address($_SESSION['E_MAIL'])) {			  // If it is valid, send the email.			mail($_SESSION['SITE_EMAIL'], "Comments from a user: ".$_SESSION['S_SUBJECT'], $_SESSION['S_MESSAGE'], "From: ".$_SESSION['E_MAIL']);		} else {				// If it does not have any spoofing code, but is not valid, send it back to the form with a warning/			  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.				header ("Location: ./contact_us.php?flg=pink");			  break;			}			}	} else {		// If "email" is not filled out, send it back to the form with a warning	  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.		header ("Location: ./contact_us.php?flg=blue");		break;	}	?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Processing e-mail</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><p>Thank you <?php echo ($fname." ".$lname); ?> for the e-mail. It has been sent off to the appropriate people.</body></html>

Now if you want it even more secure, where the user has to enter the 6 digit number that is scrambled, here you go. I got the general code from an outside link, which I won't link to here, but the description for the SQL ia as follows;

Create a table named auth_code in database test:CREATE TABLE auth_code ( request_id VARCHAR(45) NOT NULL PRIMARY KEY, auth_code CHAR(6) NOT NULL, status ENUM('W', 'A', 'E', 'N') NOT NULL DEFAULT 'W');Status code abbreviations stands for “Waiting”, “Approved”, “Expired”, “Not Approved” respectively.
I also made some improvements and corrections. If you fill out the session_init.php file properly, and make the "auth_code" in the same database you should not have any problem with the code as is. Also you will have to make a "fonts" folder and put the true type fonts you want to use in there, and make sure to write the names of the fonts in the image.php file in the variable section. Keep in mind not all true type fonts will work in php.email_form.php:
<?php	session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");  	$sFName = $_SESSION['F_NAME'];	$sLName = $_SESSION['L_NAME'];	$sEmail = $_SESSION['E_MAIL'];	$sSubject = $_SESSION['S_SUBJECT']; 	$sCompany = $_SESSION['S_COMPANY'];	$sPhone = $_SESSION['S_PHONE'];	$sMsg = $_SESSION['S_MESSAGE'];		// Generate 6 digit random number	$num = rand(100000, 999999);	$request_id = uniqid(md5(time()));	//Connect database and insert request id and number	$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');	@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');	$sql = "INSERT INTO auth_code VALUES('".$request_id."', '".$num."', 'W')";	@mysql_query($sql, $db_conn) or die('Query failed of :'.mysql_error());	mysql_close($db_conn);		// Process Error message on failed submission	$flg = "";	$error = "";		if (isset($HTTP_GET_VARS["flg"])){		$flg = $HTTP_GET_VARS["flg"];	}		switch ($flg) {		case "yellow":			$error = "That Email Address already exists in our Database.<br>Please Select Another.<br />";			break;		case "red":			$error = "You messed up";			break;		case "blue":			$error = "You forgot to place and e-mail address.";			break;		case "pink":			$error = "Please add a valid email address";			break;		case "black":			$error = "You seem to have some code we do not recognize.";			break;		case "white":			$error = "The security code you entered did not match.";			break;		default:			$error = "";	}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sending an e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><table>	<tr>		<td>			<?php				if ($error != ""){					echo ('<table id="etable"><tr><td height="50" id="eerror">');					echo ($error);				} else {					echo ('<table><tr><td  height="56px">');				}			?>								</td>				</tr>			</table>		</td>	</tr>	<tr>	<td>		<form name="email_form" method="post" action="./process_contact_us.php">		<table cellspacing="3" cellpadding="1">			<tr>				<td>					First Name:				</td>				<td >					<input name="fname" type="text" value="<?php echo ( $sFName );?>" size="25" maxlength="60" />				</td>			</tr>			<tr>				<td>					Last Name:				</td>				<td>					<input name="lname" type="text"  value="<?php  echo ( $sLName ); ?>" size="25" maxlength="60" /><br/>				</td>			<tr>					<td>					Company:				</td>				<td>					<input name="company_name" type="text" value="<?php  echo ( $sCompany ); ?>" size="25" maxlength="75" /><br/>				</td>							</tr>				<tr>				<td>					Phone Number:				</td>				<td>					<input name="phone" type="text"  value="<?php  echo ( $sPhone ); ?>" size="15" maxlength="12" />				</td>			</tr>				<tr>					<td>					E-mail:				</td>							<td>					<input name="email" type="text" id="subject" value="<?php  echo ( $sEmail ); ?>" size="56" maxlength="50" /><br/>				</td>			</tr>				 			<tr>					<td>					Subject:				</td>				<td>					<input name="subject" type="text" id="subject" value="<?php  echo ( $sSubject ); ?>" size="56" maxlength="80" /><br/>				</td>			</tr>			<tr>					<td id="etd" colspan="2">					Message:				</td>			</tr>				<tr>				<td id="efield" colspan="2">					<textarea name="msg" cols="42" rows="10" id="textarea2"><?php  echo ( $sMsg ); ?></textarea>  				</td>			</tr>			<tr>					<td colspan="2">							<INPUT TYPE="hidden" NAME="RequestId" VALUE="<?php echo($request_id)?>">					<table border=0 cellspacing="2" cellpadding="2" width="100%" >					<tr>					<td WIDTH="20%" VALIGN="top">					Type the number below:<BR>					<INPUT TYPE="text" NAME="UserNumber" MAXLENGTH=6 SIZE=20>				  </td>							<td> 														</td>					<td WIDTH="80%" VALIGN="middle">				  <IMG SRC="image.php?rid=<?php echo($request_id);?>" WIDTH=160 HEIGHT=50 BORDER=1>					</td>					</tr>					</table>					</FORM>				</td>			</tr>			<tr>				<td>					<INPUT TYPE="submit" VALUE="Submit E-mail">				</td>			</tr>		</table>			</FORM>	</td></tr></table></body></html>

image.php

<?phprequire("./include/no_caching.php");session_start();if (!isset($_SESSION['SESSION'])){	header ("Location: ../index.php");	break;}// Gather request id from querystring$request_id = isset($_GET['rid']) ? $_GET['rid'] : "0";if (strlen($request_id)!=45) $error_msg= 'Invalid number';// Connect database and get the number to be displayed$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');//Construct SQL$sql = "SELECT auth_code FROM auth_code WHERE request_id='".$request_id."' AND status='W'";$tmp_rs = @mysql_query($sql, $db_conn) or die('Query failed of '.mysql_error());// Really got such request id or someone having fun?if (mysql_num_rows($tmp_rs)==0) {		$error_msg='No matching rows...';} else {		$number = mysql_result($tmp_rs, 0, 0);}////////////////////////////// Variables /////////////////////////////////////$x = 160;											// Image width$y = 50;											// Image height$d_freq=1000;									// Number of noise Dots$l_freq= 100;									// Number of noise Lines$s_freq=20;										// Number of noise Squares$noise_selection = "random"; 	// random | fixed								   $noise_method= array("lines", "dots", "squares",);   // line | dots | squares$default_method = 2;					// If you choose fixed for $noise_selection, 0 = Lines, 1 = Dots, 2 = Squares $squ_size = 6;								// If you choose to use Squares, the size they should be.$font_selection = "random";   // random | fixed$font_folder = "./fonts/";	 // Path to fonts folder$fonts = array("mlsjn.ttf", "trebucit.ttf","hanshand.ttf");$default_font = 0;				// Array index of default font in $fonts array.$angle_selection = "random";  // random | fixed$max_angle = 10;			  // Max angle$default_angle = 0;		   // Default angle.$font_size = 30;			  // Font size in points////////////////////////////////////////////////////////////////////////////// Set fontif ($font_selection=="random") {	$font = rand(0, count($fonts)-1);		$font = $font_folder.$fonts[$font];} else {	$font = $font_folder.$fonts[$default_font];}// Set Text Angleif ($angle_selection=="random") {	$angle = rand((-1)*($max_angle/2), ($max_angle/2));} else {	$angle = $default_angle;}// Create image with specified size.$img = @ImageCreate($x, $y) or die("Couldn't create image");// Allocate colors$black = ImageColorAllocate($img, 0, 0, 0);$white = ImageColorAllocate($img, 255, 255, 255);/* Get background , noise and font color randomly from get_random_colors() function. This function returns contrary colors for readability.*/function get_random_colors() {	// $bck = array of background (R,G,B) values	// $dot = array of noise (R,G,B) values	// $txt = array of text (R,G,B) values	$bck=array(); $dot=array(); $txt=array();	// i=O =>Red | i=1 =>Green | i=2 =>Blue	for ($i=0; $i<3; $i++) {		$x = rand(0,132);		$y = rand(191,255);		array_push($bck, $x);		array_push($dot, (255-$x));		array_push($txt, $y);	}	// Return array of 3 arrays : [0..2, 0..2]	return array($bck, $dot, $txt);}$rnd_col = get_random_colors();$background = ImageColorAllocate($img, $rnd_col[0][0], $rnd_col[0][1], $rnd_col[0][2]);$dots_color = ImageColorAllocate($img, $rnd_col[1][0], $rnd_col[1][1], $rnd_col[1][2]);$text_color = ImageColorAllocate($img, $rnd_col[2][0], $rnd_col[2][1], $rnd_col[2][2]);// Stop execution if any error occured beforeif (isset($error_msg)) {	//Fill image background with white	ImageFill ($img, 100, 50, $white);	//Display error	ImageString($img, 2, 20, 10, $error_msg, $black);} else {	//Fill image with background color	ImageFill ($img, 100, 50, $background);	// Add centered text	$arr=ImageTtfbBox($font_size, $angle, $font, $number);	// Unremark the line below to see what $arr have in	// echo ("<PRE>"); print_r($arr); die();	$text_x= round(($x-(abs($arr[2]-$arr[0]))) / 2, 0);	$text_y= round(($y-(abs($arr[5]-$arr[3]))) / 2, 0);	ImageTTFText($img, $font_size, $angle, $text_x, $text_y - $arr[5], $text_color, $font, $number);	$i=0;		//<---------Noise Counter			if ($noise_selection == "random") {		$noise = rand(0, count($noise_method)-1);  			//$_SESSION['NOISE_NO'] = $noise;		$noise = $noise_method[$noise];	} else {		$noise = $noise_method[$default_method];	};		switch ($noise) {		case "lines":			$freq = $l_freq;			break;		case "dots":			$freq = $d_freq;			break;		case "squares":			$freq = $s_freq;			break;		default:			$freq = $d_freq;			break;		};		//$freq = $l_freq;		// Add Noise Points	while ($i < $freq) {		$dotX = rand(0, $x); $dotY = rand(0, $y);		switch ($noise) {		case "lines":			$line_width = rand(4,20);			if (rand(0,10)>=5) {				// Draw horizontal line				ImageLine($img, $dotX, $dotY, $dotX+$line_width, $dotY, $dots_color);			} else {				// Draw vertical line				ImageLine($img, $dotX, $dotY, $dotX, $dotY+$line_width, $dots_color);			}			break;		case "dots":			ImageSetPixel($img, $dotX, $dotY, $dots_color);			break;		case "squares":			ImageRectangle($img, $dotX - $squ_size, $dotY - $squ_size, $dotX + $squ_size, $dotY + $squ_size, $dots_color);			break;		}		$i++;
Link to comment
Share on other sites

  • 2 weeks later...
If anyone is wondering like I was on how to secure your e-mail form page here is what I put together from different sources and with a little of my own flair. If you had questions on the code found on this thread or on the w3school secure email, I will try to explain that as well.The code should actually be broken up. The processing code and the form code do not need to be together at all. One thing you need to think of, is how do I notify the user that they made a mistake, or forgot some information. I do this by redirecting the user back to the email_form.php page using the "header (Location...) command with a flag variable that correspond to the error generated. Then the error is displayed above the form.So the two very basic pages would look something like this:email_form.php
// Process Error message on failed submission	$flg = "";	$error = "";		if (isset($HTTP_GET_VARS["flg"])){		$flg = $HTTP_GET_VARS["flg"];	}		switch ($flg) {		case "yellow":			$error = "That Email Address already exists in our Database.<br>Please Select Another.<br />";			break;		case "red":			$error = "You messed up";			break;		case "blue":			$error = "You forgot to place and e-mail address.";			break;		case "pink":			$error = "Please add a valid email address";			break;		case "black":			$error = "You seem to have some code we do not recognize.";			break;		case "white":			$error = "The security code you entered did not match.";			break;		default:			$error = "";	}?>?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sending an Email</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><table>	<tr>		<td>			<?php				if ($error != ""){					echo ('<table id="etable"><tr><td height="50" id="eerror">');					echo ($error);				} else {					echo ('<table><tr><td  height="56px">');				}			?>								</td>				</tr>			</table>		</td>	</tr>	<tr>	<td>		<form name="email_form" method="post" action="./process_email.php">		<table cellspacing="3" cellpadding="1">			<tr>				<td>					First Name:				</td>				<td >					<input name="fname" type="text" value="<?php echo ( $sFName );?>" size="25" maxlength="60" />				</td>			</tr>			<tr>				<td>					Last Name:				</td>				<td>					<input name="lname" type="text"  value="<?php  echo ( $sLName ); ?>" size="25" maxlength="60" /><br/>				</td>			<tr>					<td>					Company:				</td>				<td>					<input name="company_name" type="text" value="<?php  echo ( $sCompany ); ?>" size="25" maxlength="75" /><br/>				</td>							</tr>				<tr>				<td>					Phone Number:				</td>				<td>					<input name="phone" type="text"  value="<?php  echo ( $sPhone ); ?>" size="15" maxlength="12" />				</td>			</tr>				<tr>					<td>					E-mail:				</td>				<td>					<input name="email" type="text" id="subject" value="<?php  echo ( $sEmail ); ?>" size="56" maxlength="50" /><br/>				</td>			</tr>				 			<tr>					<td>					Subject:				</td>				<td>					<input name="subject" type="text" id="subject" value="<?php  echo ( $sSubject ); ?>" size="56" maxlength="80" /><br/>				</td>			</tr>			<tr>					<td id="etd" colspan="2">					Message:				</td>			</tr>				<tr>				<td id="efield" colspan="2">					<textarea name="msg" cols="42" rows="10" id="textarea2"><?php  echo ( $sMsg ); ?></textarea>  				</td>			</tr>			<tr>					<td colspan="2">							<INPUT TYPE="hidden" NAME="RequestId" VALUE="<?php echo($request_id)?>">					</FORM>				</td>			</tr>			<tr>				<td>					<INPUT TYPE="submit" VALUE="Submit E-mail">				</td>			</tr>		</table>			</FORM>	</td></tr></table></body></html>

process_email.php

<?php		$fname = $_REQUEST["fname"];	$lname = $_REQUEST["lname"];	$email = $_REQUEST["email"];	$subject = $_REQUEST["subject"]; 	$company_name = $_REQUEST["company_name"];	$phone = $_REQUEST["phone"];	$msg = $_REQUEST["msg"];		function spamcheck($field) {	  //eregi() performs a case insensitive regular expression match	  if(eregi("to:",$field) || eregi("cc:",$field)) {		return TRUE;	} else {		return FALSE;	}  }//if "email" is filled out, send email,	if (isset($email)) {	  //check to see if the email address is invalid because is has extra code.	  $mailcheck = spamcheck($email);	  if ($mailcheck==TRUE){			// If it does have questionable code, like To; or Cc:, do this,			header ("Location: ./email_form.php?flag=red");		  break;	  } else { 		//  If not, send the email.   		mail("somebody@some_domain.com", "Subject: ".$subject, $message, "From: ".$email );	}  } else {		//if "email" is not filled out, display the form	  header ("Location: ./email_form.php?flag=red");	  break;	}	?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Processing e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><!-- Your message to display that the message went through. --><p>Thank you <?php echo ($fname." ".$lname); ?> for the e-mail. It has been sent off to the appropriate people.</body></html>

That is it in a nut shell. If you want a little more robust processing pages, use the same email_form.php page, but use this code for for your process_email.php page. Take note that any code used from this point forward you need to use sessions cookie. To make sure is it initiated, in a folder named include, place a file named session_init.php. In that file you should have <?php $_SESSION['SESSION'] = TRUE; ?> if nothing else.Some other useful things to have are:

<?php	$_SESSION['APP_MX'] = "mail.somedomain.com";	$_SESSION['APP_SERVER'] = "somedomain.com";	$_SESSION['SITE_EMAIL'] = "someone@somedomain.com";  // Where the e-mails should be sent to.		$_SESSION['MYSQL_SERVER'] = "localhost";	$_SESSION['MYSQL_LOGIN'] = "<username>"; // The one used to login into your Database.	$_SESSION['MYSQL_PASS'] = "<password>";  // The one used to login into your Database.	$_SESSION['MYSQL_DB'] = "";		$_SESSION['LOGGEDIN'] = "";	$_SESSION['USERID'] = 0;		$_SESSION['E_MAIL'] = "";	$_SESSION['F_NAME'] = "";	$_SESSION['L_NAME'] = "";			$_SESSION['SESSION'] = TRUE;	?>

process_email.php

<?php	session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");	$_SESSION['F_NAME'] = $_REQUEST["fname"];	$_SESSION['L_NAME'] = $_REQUEST["lname"];	$_SESSION['E_MAIL'] = $_REQUEST["email"];	$_SESSION['S_SUBJECT'] = $_REQUEST["subject"]; 	$_SESSION['S_COMPANY'] = $_REQUEST["company_name"];	$_SESSION['S_PHONE'] = $_REQUEST["phone"];	$_SESSION['S_MESSAGE'] = $_REQUEST["msg"];		function spamcheck($field) {		  // eregi() performs a case insensitive regular expression match		  if(eregi("to:",$field) || eregi("cc:",$field)) {				return TRUE;			} else {				return FALSE;			}	  }	// Validates according to the RFC 822 rules. (http://www.faqs.org/rfcs/rfc822.html)	function is_valid_email_address($e_mail){			$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';			$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';			$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';			$quoted_pair = '\\x5c[\\x00-\\x7f]';			$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";			$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";			$domain_ref = $atom;			$sub_domain = "($domain_ref|$domain_literal)";			$word = "($atom|$quoted_string)";			$domain = "$sub_domain(\\x2e$sub_domain)*";			$local_part = "$word(\\x2e$word)*";			$addr_spec = "$local_part\\x40$domain";			return preg_match("!^$addr_spec$!", $e_mail) ? 1 : 0;	}	//if "email" is filled out, proceed...	if (isset($_SESSION['E_MAIL'])){	  //check to see if the email address has spoofing code added.	  $mailcheck = spamcheck($email);	  // If it does, send it back to the form with a warning/		if ($mailcheck==TRUE){			$_SESSION['E_MAIL'] = ""; //Reset the email address just in case.		header ("Location: ./contact_us.php?flg=black");		  break;	  } else { 		// If it does not have questionable code, check to see if the email address is valid.			if (is_valid_email_address($_SESSION['E_MAIL'])) {			  // If it is valid, send the email.			mail($_SESSION['SITE_EMAIL'], "Comments from a user: ".$_SESSION['S_SUBJECT'], $_SESSION['S_MESSAGE'], "From: ".$_SESSION['E_MAIL']);		} else {				// If it does not have any spoofing code, but is not valid, send it back to the form with a warning/			  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.				header ("Location: ./contact_us.php?flg=pink");			  break;			}			}	} else {		// If "email" is not filled out, send it back to the form with a warning	  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.		header ("Location: ./contact_us.php?flg=blue");		break;	}	?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Processing e-mail</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><p>Thank you <?php echo ($fname." ".$lname); ?> for the e-mail. It has been sent off to the appropriate people.</body></html>

Now if you want it even more secure, where the user has to enter the 6 digit number that is scrambled, here you go. I got the general code from an outside link, which I won't link to here, but the description for the SQL ia as follows;I also made some improvements and corrections. If you fill out the session_init.php file properly, and make the "auth_code" in the same database you should not have any problem with the code as is. Also you will have to make a "fonts" folder and put the true type fonts you want to use in there, and make sure to write the names of the fonts in the image.php file in the variable section. Keep in mind not all true type fonts will work in php.email_form.php:

<?php	session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");  	$sFName = $_SESSION['F_NAME'];	$sLName = $_SESSION['L_NAME'];	$sEmail = $_SESSION['E_MAIL'];	$sSubject = $_SESSION['S_SUBJECT']; 	$sCompany = $_SESSION['S_COMPANY'];	$sPhone = $_SESSION['S_PHONE'];	$sMsg = $_SESSION['S_MESSAGE'];		// Generate 6 digit random number	$num = rand(100000, 999999);	$request_id = uniqid(md5(time()));	//Connect database and insert request id and number	$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');	@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');	$sql = "INSERT INTO auth_code VALUES('".$request_id."', '".$num."', 'W')";	@mysql_query($sql, $db_conn) or die('Query failed of :'.mysql_error());	mysql_close($db_conn);		// Process Error message on failed submission	$flg = "";	$error = "";		if (isset($HTTP_GET_VARS["flg"])){		$flg = $HTTP_GET_VARS["flg"];	}		switch ($flg) {		case "yellow":			$error = "That Email Address already exists in our Database.<br>Please Select Another.<br />";			break;		case "red":			$error = "You messed up";			break;		case "blue":			$error = "You forgot to place and e-mail address.";			break;		case "pink":			$error = "Please add a valid email address";			break;		case "black":			$error = "You seem to have some code we do not recognize.";			break;		case "white":			$error = "The security code you entered did not match.";			break;		default:			$error = "";	}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sending an e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><table>	<tr>		<td>			<?php				if ($error != ""){					echo ('<table id="etable"><tr><td height="50" id="eerror">');					echo ($error);				} else {					echo ('<table><tr><td  height="56px">');				}			?>								</td>				</tr>			</table>		</td>	</tr>	<tr>	<td>		<form name="email_form" method="post" action="./process_contact_us.php">		<table cellspacing="3" cellpadding="1">			<tr>				<td>					First Name:				</td>				<td >					<input name="fname" type="text" value="<?php echo ( $sFName );?>" size="25" maxlength="60" />				</td>			</tr>			<tr>				<td>					Last Name:				</td>				<td>					<input name="lname" type="text"  value="<?php  echo ( $sLName ); ?>" size="25" maxlength="60" /><br/>				</td>			<tr>					<td>					Company:				</td>				<td>					<input name="company_name" type="text" value="<?php  echo ( $sCompany ); ?>" size="25" maxlength="75" /><br/>				</td>							</tr>				<tr>				<td>					Phone Number:				</td>				<td>					<input name="phone" type="text"  value="<?php  echo ( $sPhone ); ?>" size="15" maxlength="12" />				</td>			</tr>				<tr>					<td>					E-mail:				</td>							<td>					<input name="email" type="text" id="subject" value="<?php  echo ( $sEmail ); ?>" size="56" maxlength="50" /><br/>				</td>			</tr>				 			<tr>					<td>					Subject:				</td>				<td>					<input name="subject" type="text" id="subject" value="<?php  echo ( $sSubject ); ?>" size="56" maxlength="80" /><br/>				</td>			</tr>			<tr>					<td id="etd" colspan="2">					Message:				</td>			</tr>				<tr>				<td id="efield" colspan="2">					<textarea name="msg" cols="42" rows="10" id="textarea2"><?php  echo ( $sMsg ); ?></textarea>  				</td>			</tr>			<tr>					<td colspan="2">							<INPUT TYPE="hidden" NAME="RequestId" VALUE="<?php echo($request_id)?>">					<table border=0 cellspacing="2" cellpadding="2" width="100%" >					<tr>					<td WIDTH="20%" VALIGN="top">					Type the number below:<BR>					<INPUT TYPE="text" NAME="UserNumber" MAXLENGTH=6 SIZE=20>				  </td>							<td> 														</td>					<td WIDTH="80%" VALIGN="middle">				  <IMG SRC="image.php?rid=<?php echo($request_id);?>" WIDTH=160 HEIGHT=50 BORDER=1>					</td>					</tr>					</table>					</FORM>				</td>			</tr>			<tr>				<td>					<INPUT TYPE="submit" VALUE="Submit E-mail">				</td>			</tr>		</table>			</FORM>	</td></tr></table></body></html>

image.php

<?phprequire("./include/no_caching.php");session_start();if (!isset($_SESSION['SESSION'])){	header ("Location: ../index.php");	break;}// Gather request id from querystring$request_id = isset($_GET['rid']) ? $_GET['rid'] : "0";if (strlen($request_id)!=45) $error_msg= 'Invalid number';// Connect database and get the number to be displayed$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');//Construct SQL$sql = "SELECT auth_code FROM auth_code WHERE request_id='".$request_id."' AND status='W'";$tmp_rs = @mysql_query($sql, $db_conn) or die('Query failed of '.mysql_error());// Really got such request id or someone having fun?if (mysql_num_rows($tmp_rs)==0) {		$error_msg='No matching rows...';} else {		$number = mysql_result($tmp_rs, 0, 0);}////////////////////////////// Variables /////////////////////////////////////$x = 160;											// Image width$y = 50;											// Image height$d_freq=1000;									// Number of noise Dots$l_freq= 100;									// Number of noise Lines$s_freq=20;										// Number of noise Squares$noise_selection = "random"; 	// random | fixed								   $noise_method= array("lines", "dots", "squares",);   // line | dots | squares$default_method = 2;					// If you choose fixed for $noise_selection, 0 = Lines, 1 = Dots, 2 = Squares $squ_size = 6;								// If you choose to use Squares, the size they should be.$font_selection = "random";   // random | fixed$font_folder = "./fonts/";	 // Path to fonts folder$fonts = array("mlsjn.ttf", "trebucit.ttf","hanshand.ttf");$default_font = 0;				// Array index of default font in $fonts array.$angle_selection = "random";  // random | fixed$max_angle = 10;			  // Max angle$default_angle = 0;		   // Default angle.$font_size = 30;			  // Font size in points////////////////////////////////////////////////////////////////////////////// Set fontif ($font_selection=="random") {	$font = rand(0, count($fonts)-1);		$font = $font_folder.$fonts[$font];} else {	$font = $font_folder.$fonts[$default_font];}// Set Text Angleif ($angle_selection=="random") {	$angle = rand((-1)*($max_angle/2), ($max_angle/2));} else {	$angle = $default_angle;}// Create image with specified size.$img = @ImageCreate($x, $y) or die("Couldn't create image");// Allocate colors$black = ImageColorAllocate($img, 0, 0, 0);$white = ImageColorAllocate($img, 255, 255, 255);/* Get background , noise and font color randomly from get_random_colors() function. This function returns contrary colors for readability.*/function get_random_colors() {	// $bck = array of background (R,G, values	// $dot = array of noise (R,G, values	// $txt = array of text (R,G, values	$bck=array(); $dot=array(); $txt=array();	// i=O =>Red | i=1 =>Green | i=2 =>Blue	for ($i=0; $i<3; $i++) {		$x = rand(0,132);		$y = rand(191,255);		array_push($bck, $x);		array_push($dot, (255-$x));		array_push($txt, $y);	}	// Return array of 3 arrays : [0..2, 0..2]	return array($bck, $dot, $txt);}$rnd_col = get_random_colors();$background = ImageColorAllocate($img, $rnd_col[0][0], $rnd_col[0][1], $rnd_col[0][2]);$dots_color = ImageColorAllocate($img, $rnd_col[1][0], $rnd_col[1][1], $rnd_col[1][2]);$text_color = ImageColorAllocate($img, $rnd_col[2][0], $rnd_col[2][1], $rnd_col[2][2]);// Stop execution if any error occured beforeif (isset($error_msg)) {	//Fill image background with white	ImageFill ($img, 100, 50, $white);	//Display error	ImageString($img, 2, 20, 10, $error_msg, $black);} else {	//Fill image with background color	ImageFill ($img, 100, 50, $background);	// Add centered text	$arr=ImageTtfbBox($font_size, $angle, $font, $number);	// Unremark the line below to see what $arr have in	// echo ("<PRE>"); print_r($arr); die();	$text_x= round(($x-(abs($arr[2]-$arr[0]))) / 2, 0);	$text_y= round(($y-(abs($arr[5]-$arr[3]))) / 2, 0);	ImageTTFText($img, $font_size, $angle, $text_x, $text_y - $arr[5], $text_color, $font, $number);	$i=0;		//<---------Noise Counter			if ($noise_selection == "random") {		$noise = rand(0, count($noise_method)-1);  			//$_SESSION['NOISE_NO'] = $noise;		$noise = $noise_method[$noise];	} else {		$noise = $noise_method[$default_method];	};		switch ($noise) {		case "lines":			$freq = $l_freq;			break;		case "dots":			$freq = $d_freq;			break;		case "squares":			$freq = $s_freq;			break;		default:			$freq = $d_freq;			break;		};		//$freq = $l_freq;		// Add Noise Points	while ($i < $freq) {		$dotX = rand(0, $x); $dotY = rand(0, $y);		switch ($noise) {		case "lines":			$line_width = rand(4,20);			if (rand(0,10)>=5) {				// Draw horizontal line				ImageLine($img, $dotX, $dotY, $dotX+$line_width, $dotY, $dots_color);			} else {				// Draw vertical line				ImageLine($img, $dotX, $dotY, $dotX, $dotY+$line_width, $dots_color);			}			break;		case "dots":			ImageSetPixel($img, $dotX, $dotY, $dots_color);			break;		case "squares":			ImageRectangle($img, $dotX - $squ_size, $dotY - $squ_size, $dotX + $squ_size, $dotY + $squ_size, $dots_color);			break;		}		$i++;<br /I am a veteran PHP programmer of at least 7 or 8 days experience! I too had some questions around the eregi() issue but, having read most of the posts on this thread (and even understood some of them), I think my questions are now answered, plus a few I hadn't got round to thinking about yet.Thanks everyone.Kind regardsTony
Link to comment
Share on other sites

Just realize part of my last post was cut short, guess it was a bit long. So here is just the code for the three files you need, not including the session_init file, and the auth_code entry in database which has already mentioned.email.php

<?php	session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");  	$sFName = $_SESSION['F_NAME'];	$sLName = $_SESSION['L_NAME'];	$sEmail = $_SESSION['E_MAIL'];	$sSubject = $_SESSION['S_SUBJECT'];	$sCompany = $_SESSION['S_COMPANY'];	$sPhone = $_SESSION['S_PHONE'];	$sMsg = $_SESSION['S_MESSAGE'];		// Generate 6 digit random number	$num = rand(100000, 999999);	$request_id = uniqid(md5(time()));	//Connect database and insert request id and number	$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');	@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');	$sql = "INSERT INTO auth_code VALUES('".$request_id."', '".$num."', 'W')";	@mysql_query($sql, $db_conn) or die('Query failed of :'.mysql_error());	mysql_close($db_conn);		// Process Error message on failed submission	$flg = "";	$error = "";		if (isset($HTTP_GET_VARS["flg"])){		$flg = $HTTP_GET_VARS["flg"];	}		switch ($flg) {		case "yellow":			$error = "That Email Address already exists in our Database.<br>Please Select Another.<br />";			break;		case "red":			$error = "You messed up";			break;		case "blue":			$error = "You forgot to place and e-mail address.";			break;		case "pink":			$error = "Please add a valid email address";			break;		case "black":			$error = "You seem to have some code we do not recognize.";			break;		case "white":			$error = "The security code you entered did not match.";			break;		default:			$error = "";	}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sending an e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><table>	<tr>		<td>			<?php				if ($error != ""){					echo ('<table id="etable"><tr><td height="50" id="eerror">');					echo ($error);				} else {					echo ('<table><tr><td  height="56px">');				}			?>								</td>				</tr>			</table>		</td>	</tr>	<tr>	<td>		<form name="email_form" method="post" action="./process_email.php">		<table cellspacing="3" cellpadding="1">			<tr>				<td>					First Name:				</td>				<td >					<input name="fname" type="text" value="<?php echo ( $sFName );?>" size="25" maxlength="60" />				</td>			</tr>			<tr>				<td>					Last Name:				</td>				<td>					<input name="lname" type="text"  value="<?php  echo ( $sLName ); ?>" size="25" maxlength="60" /><br/>				</td>			<tr>					<td>					Company:				</td>				<td>					<input name="company_name" type="text" value="<?php  echo ( $sCompany ); ?>" size="25" maxlength="75" /><br/>				</td>							</tr>				<tr>				<td>					Phone Number:				</td>				<td>					<input name="phone" type="text"  value="<?php  echo ( $sPhone ); ?>" size="15" maxlength="12" />				</td>			</tr>				<tr>					<td>					E-mail:				</td>							<td>					<input name="email" type="text" id="subject" value="<?php  echo ( $sEmail ); ?>" size="56" maxlength="50" /><br/>				</td>			</tr>							<tr>					<td>					Subject:				</td>				<td>					<input name="subject" type="text" id="subject" value="<?php  echo ( $sSubject ); ?>" size="56" maxlength="80" /><br/>				</td>			</tr>			<tr>					<td id="etd" colspan="2">					Message:				</td>			</tr>				<tr>				<td id="efield" colspan="2">					<textarea name="msg" cols="42" rows="10" id="textarea2"><?php  echo ( $sMsg ); ?></textarea>  				</td>			</tr>			<tr>					<td colspan="2">							<INPUT TYPE="hidden" NAME="RequestId" VALUE="<?php echo($request_id)?>">					<table border=0 cellspacing="2" cellpadding="2" width="100%" >					<tr>					<td WIDTH="20%" VALIGN="top">					Type the number below:<BR>					<INPUT TYPE="text" NAME="UserNumber" MAXLENGTH=6 SIZE=20>				  </td>							<td>														</td>					<td WIDTH="80%" VALIGN="middle">				  <IMG SRC="image.php?rid=<?php echo($request_id);?>" WIDTH=160 HEIGHT=50 BORDER=1>					</td>					</tr>					</table>					</FORM>				</td>			</tr>			<tr>				<td>					<INPUT TYPE="submit" VALUE="Submit E-mail">				</td>			</tr>		</table>			</FORM>	</td></tr></table></body></html>

image.php

<?php// Image should expire immediatelyheader('Content-type:image/png');header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');header('Cache-Control: no-store, no-cache, must-revalidate');header('Cache-Control: post-check=0, pre-check=0', false);session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");// Gather request id from querystring$request_id = isset($_GET['rid']) ? $_GET['rid'] : "0";if (strlen($request_id)!=45) $error_msg= 'Invalid number';// Connect database and get the number to be displayed$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');//Construct SQL$sql = "SELECT auth_code FROM auth_code WHERE request_id='".$request_id."' AND status='W'";$tmp_rs = @mysql_query($sql, $db_conn) or die('Query failed of '.mysql_error());// Really got such request id or someone having fun?if (mysql_num_rows($tmp_rs)==0) {		$error_msg='No matching rows...';} else {		$number = mysql_result($tmp_rs, 0, 0);}////////////////////////////// Variables /////////////////////////////////////$x = 160;											// Image width$y = 50;											// Image height$d_freq=1000;									// Number of noise Dots$l_freq= 100;									// Number of noise Lines$s_freq=20;										// Number of noise Squares$noise_selection = "random"; 	// random | fixed								   $noise_method= array("lines", "dots", "squares",);   // line | dots | squares$default_method = 2;					// If you choose fixed for $noise_selection, 0 = Lines, 1 = Dots, 2 = Squares $squ_size = 6;								// If you choose to use Squares, the size they should be.$font_selection = "random";   // random | fixed$font_folder = "./fonts/";	 // Path to fonts folder$fonts = array("mlsjn.ttf", "trebucit.ttf","hanshand.ttf");$default_font = 0;				// Array index of default font in $fonts array.$angle_selection = "random";  // random | fixed$max_angle = 10;			  // Max angle$default_angle = 0;		   // Default angle.$font_size = 30;			  // Font size in points////////////////////////////////////////////////////////////////////////////// Set fontif ($font_selection=="random") {	$font = rand(0, count($fonts)-1);		$font = $font_folder.$fonts[$font];} else {	$font = $font_folder.$fonts[$default_font];}// Set Text Angleif ($angle_selection=="random") {	$angle = rand((-1)*($max_angle/2), ($max_angle/2));} else {	$angle = $default_angle;}// Create image with specified size.$img = @ImageCreate($x, $y) or die("Couldn't create image");// Allocate colors$black = ImageColorAllocate($img, 0, 0, 0);$white = ImageColorAllocate($img, 255, 255, 255);/* Get background , noise and font color randomly from get_random_colors() function. This function returns contrary colors for readability.*/function get_random_colors() {	// $bck = array of background (R,G,B) values	// $dot = array of noise (R,G,B) values	// $txt = array of text (R,G,B) values	$bck=array(); $dot=array(); $txt=array();	// i=O =>Red | i=1 =>Green | i=2 =>Blue	for ($i=0; $i<3; $i++) {		$x = rand(0,132);		$y = rand(191,255);		array_push($bck, $x);		array_push($dot, (255-$x));		array_push($txt, $y);	}	// Return array of 3 arrays : [0..2, 0..2]	return array($bck, $dot, $txt);}$rnd_col = get_random_colors();$background = ImageColorAllocate($img, $rnd_col[0][0], $rnd_col[0][1], $rnd_col[0][2]);$dots_color = ImageColorAllocate($img, $rnd_col[1][0], $rnd_col[1][1], $rnd_col[1][2]);$text_color = ImageColorAllocate($img, $rnd_col[2][0], $rnd_col[2][1], $rnd_col[2][2]);// Stop execution if any error occured beforeif (isset($error_msg)) {	//Fill image background with white	ImageFill ($img, 100, 50, $white);	//Display error	ImageString($img, 2, 20, 10, $error_msg, $black);} else {	//Fill image with background color	ImageFill ($img, 100, 50, $background);	// Add centered text	$arr=ImageTtfbBox($font_size, $angle, $font, $number);	// Unremark the line below to see what $arr have in	// echo ("<PRE>"); print_r($arr); die();	$text_x= round(($x-(abs($arr[2]-$arr[0]))) / 2, 0);	$text_y= round(($y-(abs($arr[5]-$arr[3]))) / 2, 0);	ImageTTFText($img, $font_size, $angle, $text_x, $text_y - $arr[5], $text_color, $font, $number);	$i=0;		//<---------Noise Counter			if ($noise_selection == "random") {		$noise = rand(0, count($noise_method)-1);  			//$_SESSION['NOISE_NO'] = $noise;		$noise = $noise_method[$noise];	} else {		$noise = $noise_method[$default_method];	};		switch ($noise) {		case "lines":			$freq = $l_freq;			break;		case "dots":			$freq = $d_freq;			break;		case "squares":			$freq = $s_freq;			break;		default:			$freq = $d_freq;			break;		};		//$freq = $l_freq;		// Add Noise Points	while ($i < $freq) {		$dotX = rand(0, $x); $dotY = rand(0, $y);		switch ($noise) {		case "lines":			$line_width = rand(4,20);			if (rand(0,10)>=5) {				// Draw horizontal line				ImageLine($img, $dotX, $dotY, $dotX+$line_width, $dotY, $dots_color);			} else {				// Draw vertical line				ImageLine($img, $dotX, $dotY, $dotX, $dotY+$line_width, $dots_color);			}			break;		case "dots":			ImageSetPixel($img, $dotX, $dotY, $dots_color);			break;		case "squares":			ImageRectangle($img, $dotX - $squ_size, $dotY - $squ_size, $dotX + $squ_size, $dotY + $squ_size, $dots_color);			break;		}		$i++;	}}//Finalize the image. Free memoryImagePNG($img); ImageDestroy($img);?>

process_email.php

<?php// Image should expire immediatelyheader('Content-type:image/png');header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');header('Cache-Control: no-store, no-cache, must-revalidate');header('Cache-Control: post-check=0, pre-check=0', false);session_start();	if (!isset($_SESSION['SESSION'])) require ( "./include/session_init.php");	$_SESSION['F_NAME'] = $_REQUEST["fname"];	$_SESSION['L_NAME'] = $_REQUEST["lname"];	$_SESSION['E_MAIL'] = $_REQUEST["email"];	$_SESSION['S_SUBJECT'] = $_REQUEST["subject"]; 	$_SESSION['S_COMPANY'] = $_REQUEST["company_name"];	$_SESSION['S_PHONE'] = $_REQUEST["phone"];	$_SESSION['S_MESSAGE'] = $_REQUEST["msg"];		// Gather request id from form data	$request_id = $_POST['RequestId'];	$user_number = trim($_POST['UserNumber']);	if (strlen($request_id)!=45){		$_SESSION['E_MAIL'] = ""; //Reset the email address just in case.		header ("Location: ./contact_us.php?flg=white");	}		// Gather request id from form data	$request_id = $_POST['RequestId'];	$user_number = trim($_POST['UserNumber']);	if (strlen($request_id)!=45) die('Invalid number');	// Connect database and get the number to be displayed	$db_conn = @mysql_connect($_SESSION['MYSQL_SERVER'], $_SESSION['MYSQL_LOGIN'], $_SESSION['MYSQL_PASS']) or die('MySQL Server Not Started');	@mysql_select_db($_SESSION['MYSQL_DB']) or die('Database not created');	//Construct SQL	$sql = "SELECT auth_code FROM auth_code WHERE request_id='".$request_id."' AND status='W'";	$tmp_rs = @mysql_query($sql, $db_conn) or die('Query failed of '.mysql_error());	$number = mysql_result($tmp_rs, 0, 0);	// Check numbers	if ($number==$user_number) {	// Update status as 'Approved'	@mysql_query("UPDATE auth_code SET status='A' WHERE request_id='".$request_id."'") or die("Database update failed");	mysql_close($db_conn);	//if "email" is filled out, proceed...		if (isset($_SESSION['E_MAIL'])){		  //check to see if the email address has spoofing code added.		  $mailcheck = spamcheck($email);		  // If it does, send it back to the form with a warning/			if ($mailcheck==TRUE){				$_SESSION['E_MAIL'] = ""; //Reset the email address just in case.			header ("Location: ./contact_us.php?flg=black");			  break;		  } else { 				// If it does not, check to see if the email address is valid.				if (is_valid_email_address($_SESSION['E_MAIL'])) {				  // If it is valid, send the email.				mail($_SESSION['SITE_EMAIL'], "Comments from a Bodington.ca user: ".$_SESSION['S_SUBJECT'], $_SESSION['S_MESSAGE'], "From: ".$_SESSION['E_MAIL']);			} else {					// If it does not have any spoofing code, but is not valid, send it back to the form with a warning/				  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.					header ("Location: ./contact_us.php?flg=pink");				  break;				}	  }		} else {			// If "email" is not filled out, send it back to the form with a warning		  $_SESSION['E_MAIL'] = ""; //Reset the email address just in case.			header ("Location: ./contact_us.php?flg=blue");			break;		}	} else {	// Update status as 'Not Approved'	@mysql_query("UPDATE auth_code SET status='N' WHERE request_id='".$request_id."'") or die("Database update failed");	mysql_close($db_conn);	header ("Location: ./contact_us.php?flg=white");	  break;	}		function spamcheck($field) {		  // eregi() performs a case insensitive regular expression match		  if(eregi("to:",$field) || eregi("cc:",$field)) {				return TRUE;			} else {				return FALSE;			}	  }	// Validates according to the RFC 822 rules. (http://www.faqs.org/rfcs/rfc822.html)	function is_valid_email_address($e_mail){			$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';			$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';			$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';			$quoted_pair = '\\x5c[\\x00-\\x7f]';			$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";			$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";			$domain_ref = $atom;			$sub_domain = "($domain_ref|$domain_literal)";			$word = "($atom|$quoted_string)";			$domain = "$sub_domain(\\x2e$sub_domain)*";			$local_part = "$word(\\x2e$word)*";			$addr_spec = "$local_part\\x40$domain";			return preg_match("!^$addr_spec$!", $e_mail) ? 1 : 0;	}?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Sent the e-mail-1</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body><!-- The message you want to display to tell the use the e-mil has been sent. --><p>Thank you for your comments, someone will the reviewing them shortly.</p></body></html>

EnjoyAnd to answer the original question;eregi() which stands for "Case insensitive regular expression match". In this case it checks to see if the "to:" pattern or the "cc:" pattern is present in the e-mail field, which would suggest that someone is inject code it your e-mailing system. This also cover "bcc:" because it also contains "cc:". In short is the first line of defence.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...