Jump to content

PHP Email form and reCaptcha


cyberdyne2

Recommended Posts

I have an email form with file attachment and I've had a nightmare of a time trying to incorporate reCaptcha into it.

I think this is mainly because the post action"" doesn't use an external file but inline code (hope i'm making sense!?)

 

I've managed to get the form to appear correct, but without the below code, it doesn't function.

The code is below. Can anyone please tell me where to insert (no jokes please!) the reCaptcha code (posted at end).

 

Many thanks in advance.

 

<?php
session_start();
function print_form(){
?>
        <span><span class="required">*</span>Required Fields</span>
<form method="post" action="<?php echo $_SERVER[’PHP_SELF’];?>" id="uploadform" enctype="multipart/form-data">
<span><label for="namefrom">Name <span class="required">*</span></label>
<input name="namefrom" style="border-width:2; border-color:#006600" id="namefrom" type="text" class="field" value="<?= $_SESSION['myForm']['namefrom']; ?>" tabindex="1"/></span>
<span><label for="emailfrom">Email <span class="required">*</span></label>
<input name="emailfrom" style="border-width:2; border-color:#006600" id="emailfrom" type="text" class="field" value="<?= $_SESSION['myForm']['emailfrom']; ?>" tabindex="3"/></span>
<span><label for="subject">Subject <span class="required">*</span></label>
<input name="subject" style="border-width:2; border-color:#006600" id="subject" type="text" class="field" value="<?= $_SESSION['myForm']['subject']; ?>" tabindex="5"/></span>
<span><label for="comments">Message <span class="required">*</span></label>
<textarea name="comments" style="border-width:2; border-color:#006600" id="comments" rows="3" cols="8" class="field" tabindex="6"><?= $_SESSION['myForm']['comments']; ?></textarea></span>
<span><label for="attachment" style="border-width:2; border-color:#006600">(1 file, max size 600kb, only .jpg or .jpeg)</label>
<input name="attachment" style="border-width:2; border-color:#006600" id="attachment" type="file" tabindex="7">
    <?php
             require_once('recaptchalib.php');
             $publickey = "your_public_key"; // you got this from the signup page
             echo recaptcha_get_html($publickey);
            ?>
      <span><input type="submit" name="submit" id="submit" value="Send"  tabindex="8"/>  <input type="reset" name="reset" id="submit" value="Reset" tabindex="9"/></span>
<span><input type="hidden" name="submitted"  value="true" /></span>
</form>
<?php
}
function process_form() {
$to = "address1@domain.ltd";
$subject = trim($_POST['subject']);
$namefrom = trim($_POST['namefrom']);
$emailfrom = trim($_POST['emailfrom']);
$comments = trim($_POST['comments']);
$allowtypes=array("jpeg", "jpg");
$requirefile="false";
$max_file_size="600";
$thanksmessage="Email sent, we will reply a.s.a.p.";
$errors = array(); //Initialize error array
if (empty($_POST['namefrom']) ) {
	$errors[]='You forgot to enter your name';
	}
if (empty($_POST['emailfrom']) ) {
	$errors[]='You forgot to enter your email';
	} else {
	if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['emailfrom'])))) {
		$errors[]='Please enter a valid email address';
	} // if eregi
} // if empty email
if (empty($_POST['subject']) ) {
	$errors[]='You forgot to enter a subject';
	}
if (empty($_POST['comments']) ) {
	$errors[]='You forgot to enter your message';
	}
if($requirefile=="true") {
	if($_FILES['attachment']['error']==4) {
		$errors[]='You forgot to attach a file';
	}
}
if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) {
		// basename -- Returns filename component of path
		$filename = basename($_FILES['attachment']['name']);
		$ext = substr($filename, strrpos($filename, '.') + 1);
		$filesize=$_FILES['attachment']['size'];
		$max_bytes=$max_file_size*600;
if (!in_array($ext, $allowtypes)) {
			$errors[]="Invalid extension for your file: <strong>".$filename."</strong>";
	} elseif($filesize > $max_bytes) {
			$errors[]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
		}
} // if !empty FILES
if (empty($errors)) { //If everything is OK
	$fileatt      = $_FILES['attachment']['tmp_name'];
	$fileatt_type = $_FILES['attachment']['type'];
	$fileatt_name = $_FILES['attachment']['name'];
        $headers = "From: ".$emailfrom."\n";
        $headers.= "Bcc: address2@domain.ltd"
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
        $headers .= "\nMIME-Version: 1.0\n" .
                    "Content-Type: multipart/mixed;\n" .
                    " boundary=\"{$mime_boundary}\"";
        $message ="This is a multi-part message in MIME format.\n\n";
        $message.="--{$mime_boundary}\n";
        $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
        $message.="Content-Transfer-Encoding: 7bit\n\n";
        $message.="You have a new email:\n\n";
        $message.="From: ".$namefrom."\n";
        $message.="Email address: ".$emailfrom."\n\n";
#		  $message.="Company: ".$company."\n";
#		  $message.="Phone: ".$phone."\n";
        $message.="Message: ".$comments."\n\n";
	if (is_uploaded_file($fileatt)) {
	  $file = fopen($fileatt,'rb');
	  $data = fread($file,filesize($fileatt));
	  fclose($file);
	  $data = chunk_split(base64_encode($data));
	  $message .= "--{$mime_boundary}\n" .
	              "Content-Type: {$fileatt_type};\n" .
	              " name=\"{$fileatt_name}\"\n" .
	              //"Content-Disposition: attachment;\n" .
	              //" filename=\"{$fileatt_name}\"\n" .
	              "Content-Transfer-Encoding: base64\n\n" .
	              $data . "\n\n" .
	              "--{$mime_boundary}--\n";
	}
	$envs = array("HTTP_USER_AGENT", "REMOTE_ADDR", "REMOTE_HOST");
	foreach ($envs as $env)
	$message .= "$env: $_SERVER[$env]\n";
	if(!mail($to,$subject,$message,$headers)) {
		exit("Mail could not be sent. Sorry! An error has occurred, please report this to the website administrator.\n");
	} else {
		echo '<div id="formfeedback"><!--<h3>Thank You!--></h3><p>'. $thanksmessage .'</p></div>';
		unset($_SESSION['myForm']);
		print_form();
	} // end of if !mail
} else { //report the errors
	echo '<div id="formfeedback"><b>Error!</b><br />';
	foreach ($errors as $msg) { //prints each error
			echo " - $msg<br />\n";
		} // end of foreach
	echo '</div>';
	print_form();
} //end of if(empty($errors))
} // end of process_form()
?>

 

reCaptcha:

  <?php
  require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }
  ?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.