SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Enthusiast RSBomber's Avatar
    Join Date
    Oct 2005
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Form to email with attachment

    I'm having a difficult time figuring this one out and could definitely use some help. I have a simple form that includes a file upload. I'm getting the contents of the file using file_get_contents() then chunk_split() and base64_encode(). I am validating the input fields using a simple validator.class file. I am unable to validate the file field for some reason (probably related to the bigger issue of not being able to send). Any light you might be able to help shed will be greatly appreciated.

    Here's the basic form page (index.php):
    Code:
    <?php
    	$email_submit = $_POST['email_submit'];	
    
    	if ($email_submit != null) {
    		// process form once submitted
    		include('send_contact.php');
    	}
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <style type="text/css">
    .required {color:#CC0033; font-weight:bold; }
    </style>
    </head>
    <body>      
    
            <?php if ($thankYouVar == null) { ?>       
    
            <form id="general" action="<?php echo $PHP_SELF; ?>" method="post">
              <input type="hidden" name="subject" value="JCAmericana Web Inquiry" />
              <input type="hidden" name="email_submit" value="1" />
    
              <fieldset>
              <div>
              
                <label for="name"><?php if ($error_name != null) { ?><span class='required'><?php } ?>Name: <span class="error">*</span><?php if ($error_name != null) { ?></span><?php } ?></label>
                <input id="name" name="name" value="<?php  echo $name; ?>" type="text" maxlength="50" />
    
                <label for="email"><?php if ($error_email != null) { ?><span class='required'><?php } ?>E-mail: <span class="error">*</span><?php if ($error_email != null) { ?></span><?php } ?></label>
                <input id="email" name="email" value="<?php  echo $email; ?>" type="text" maxlength="30" />
    
              	<?php if ($error_email2 != null) { ?>
                  <p><span class='required'><?php echo $error_email2; ?></span></p>
                <? } ?>
    
                <label for="message"><?php if ($error_message != null) { ?><span class='required'><?php } ?>Message: <span class="error">*</span><?php if ($error_message != null) { ?></span><?php } ?></label>
                <textarea id="message" name="message" cols="40" rows="5"><?php  echo $message; ?></textarea>
    
              	<label for="photo">Upload Photo</label>
                <input type="file" name="photo" id="photo" value="<?php  echo $filename; ?>" />
                <?php if ($error_filename2 != null) { ?>
                  <p><span class='required'><?php echo $error_filename2; ?></span></p>
                <? } ?>
    
              </div>
              </fieldset>
    
              <fieldset>
              <input type="submit" value="Submit" class="btnNormal" onmouseout="this.className='btnNormal'" onmouseover="this.className='btnHover'" />
              </fieldset>
    
              </form>
    
            <?php } else { ?>
    
            <h2>Thanks!</h2>
            <p>Thank you message goes here...</p>
                   
            <?php } ?>
    </body>
    </html>
    Here's the mailer (send_contact.php) with limited comments... sorry.
    Code:
    <?php
    
    require_once('include/FormValidator.class.inc');
    
    // Define post fields into simple variables
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $subject = $_POST['subject'];
    
    // --------------------------------
    
    //Gather file data and other things
    $tmp = $_FILES['photo']['tmp_name'];
    $sep = md5(time());
    $filename = $_FILES['photo']['name'];
    
    $filedata = file_get_contents($tmp); //Get file contents
    $fdata = chunk_split(base64_encode($filedata)); //Encode data into text form
    
    // --------------------------------
    
    $to = "someone@somewhere.com";
    
    $fv = new FormValidator();
    
    // Setting the error counter to one
    $total_errors = 0;
    if ($fv->isEmpty($name)) {
    	$error_name = "name";
    	$total_errors += 1;
    }
    
    if ($fv->isEmpty($email)) {
    	$error_email = "email";
    	$total_errors += 1;
    }elseif ($fv->isEmailAddress($email)) {
    	$error_email = "email";
    	$error_email2 = "Please enter a valid email address.";
    	unset($email);
    	$total_errors += 1;
    }
    
    if ($fv->isEmpty($message)) {
    	$error_message = "message";
    	$total_errors += 1;
    }
    
    if ($fv->isEmpty($subject)) {
    	$error_subject = "subject";
    	$total_errors += 1;
    }
    
    // --------------------------------
    //Determine mime type
    if ($filename != null) {
    	if ($fv->isValidFile($filename)) {
    		$error_filename = "photo";
    		$error_filename2 = "Invalid file type (JPG or GIF files only)";
    		unset($filename);
    		$total_errors += 1;
    	}
    }
    // --------------------------------
    
    $error_array = array("$error_name", "$error_email", "$error_message", "$error_subject", "$error_filename");
    if ($total_errors > 0) {
    	unset($email_submit);
    } else {
    	$mailBody = "Name: \r\n" . $name . "\r\n\r\n" . "Email: \r\n" . $email . "\r\n\r\n" . "Message: \r\n" . $message . "\r\n\r\n";	
    
    // --------------------------------
    //Begin the headers
    $headers = "From: \"From Name\" <{$email}>
    MIME-Version: 1.0
    Content-Type: Multipart/Mixed;
    	boundary=\"$sep\"
    
    charset=\"iso-8859-1\"
    Content-Transfer-Encoding: 7bit
    
    --$sep
    Content-Type: $mime_type;
    	name=\"$filename\"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
    		filename=\"$filename\"
    		
    $fdata
    --$sep";
    
    // --------------------------------
    
    // Let's mail the user!
    	mail($to, $subject, $mailBody, 
    	$headers);
    	$thankYouVar = "1";
    }
    
    ?>

    Here's the validator (FormValidator.class.inc)
    - Basic stuff here... except for the isValidFile() function
    Code:
    <?php
    
    // FormValidator.class.inc
    // class to perform form validation
    
    class FormValidator {
    	//
    	// private variables
    	// 
    	
    	var $_errorList;
    
    	//
    	// methods (private)
    	// 
    	
    	// function to get the value of a variable (field)
    	function _getValue($field) {
    		global ${$field};
    		return ${$field};
    	}
    
    	//
    	// methods (public)
    	// 
    
    	// constructor
    	// reset error list
    	function FormValidator() {
    		$this->resetErrorList();
    	}
    	
    	// check whether input is empty
    	function isEmpty($field) {
    		$value = $field;
    		if (trim($value) == "") {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	// check whether input is a string
    	function isString($field) {
    		$value = $field;
    		if(!is_string($value)) {
    			return false;
    		} else {
    			return true;
    		}
    	}
    
    	// check whether input is a number
    	function isNumber($field) {
    		$value = $field;
    		if(!is_numeric($value)) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	// check whether input is an integer
    	function isInteger($field) {
    		$value = $field;
    		if(!is_integer($value)) {
    			return false;
    		} else {
    			return true;
    		}
    	}
    
    	// check whether input is a float
    	function isFloat($field) {
    		$value = $field;
    		if(!is_float($value)) {
    			return false;
    		} else {
    			return true;
    		}
    	}
    	
    	// check whether input is alphabetic
    	function isAlpha($field) {
    		$value = $field;
    		echo $value;
    		echo "<br>";
    		$pattern = "/^[a-zA-Z]+$/";
    		if(preg_match($pattern, $value)) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	// check whether input is within a valid numeric range
    	function isWithinRange($field, $min, $max) {
    		$value = $field;
    		if(!is_numeric($value) || $value < $min || $value > $max) {
    			return false;
    		} else {
    			return true;
    		}
    	}
    	
    	// check whether input is a valid email address
    	function isEmailAddress($field) {
    		$value = $field;
    		$pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
    		if(preg_match($pattern, $value)) {
    			return false;
    		} else {
    			return true;
    		}
    	}
    	
    	// check to make sure the file is valid
    	function isValidFile($filename) {
    			
    		$ext = explode('.', $filename);
    		$ext = $ext[1];
    
    		if($ext == "JPG" || $ext == "jpg" || $ext == "JPEG" || $ext == "jpeg") {
    			$mime_type = "image/jpeg";
    			return true;
    		}
    		elseif($ext == "gif" || $ext == "GIF") {
    			$mime_type = "image/gif";
    			return true;
    		}
    		else {
    			return false;
    		}
    	}
    	
    	
    	// return the current list of errors
    	function getErrorList() {
    		return $this->_errorList;
    	}
    	
    	// check whether any errors have occurred in validation
    	// returns Boolean
    	function isError() {
    		if (sizeof($this->_errorList) > 0) {
    			return true;
    		} else {
    			return false;
    		}
    	}
    
    	// reset the error list
    	function resetErrorList() {
    		$this->_errorList = array();
    	}
    	
    // end 
    }
    
    ?>
    I am receiving the following error:
    Warning: mail(): Bad parameters to mail() function, mail not sent. in /path/to/file/goes/here/send_contact.php on line 98

    Line 98 is the actual mail function, so I think it's balking at the headers creation.

    Thanks in advance for taking a look at this and helping me out.

  2. #2
    An average geek earl-grey's Avatar
    Join Date
    Mar 2005
    Location
    Ukraine
    Posts
    1,403
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Have you tried comenting the code related to file attaching? Did it remove the error?

  3. #3
    SitePoint Enthusiast RSBomber's Avatar
    Join Date
    Oct 2005
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah... the form processor works great without the attachment stuff added into the mix. I use this processor on a lot of client sites and it works well. I'm sure there are better approaches and more secure techniques/error-checking that can be added... but that's always the case. I'm definitely open to suggestions on that front as well.

    Thanks

  4. #4
    An average geek earl-grey's Avatar
    Join Date
    Mar 2005
    Location
    Ukraine
    Posts
    1,403
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:
    PHP Code:
    $headers str_replace("\n""\r\n"$headers); 

  5. #5
    SitePoint Enthusiast RSBomber's Avatar
    Join Date
    Oct 2005
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Where? After the headers are assigned like this?

    Code:
    ...
    
    //Begin the headers
    $headers = "From: \"From Name\" <{$email}>
    MIME-Version: 1.0
    Content-Type: Multipart/Mixed;
    	boundary=\"$sep\"
    
    charset=\"iso-8859-1\"
    Content-Transfer-Encoding: 7bit
    
    --$sep
    Content-Type: $mime_type;
    	name=\"$filename\"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
    		filename=\"$filename\"
    		
    $fdata
    --$sep";
    
    
    $headers = str_replace("\n", "\r\n", $headers); 
    
    ...

  6. #6
    SitePoint Addict
    Join Date
    Feb 2004
    Location
    Staffordshire, UK & Florida, USA
    Posts
    314
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are you sure that the file is actually being uploaded? I thought the form tag should contain an enctype attribute:

    <form id="general" action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">

    According to the PHP manual:
    Note: Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.

  7. #7
    SitePoint Guru DenverDave's Avatar
    Join Date
    Feb 2001
    Location
    Denver, Colorado
    Posts
    630
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    We had a somewhat similar discussion going here:
    http://www.sitepoint.com/forums/showthread.php?t=500050

    The inspiration for me came from:
    http://4wordsystems.com/php_mail_attachment.php

    Interesting - I was going to send them some $ for the tutorial, but their purchase button does not seem to be working.

  8. #8
    An average geek earl-grey's Avatar
    Join Date
    Mar 2005
    Location
    Ukraine
    Posts
    1,403
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by RSBomber View Post
    Where? After the headers are assigned like this?

    Code:
    ...
    
    //Begin the headers
    $headers = "From: \"From Name\" <{$email}>
    MIME-Version: 1.0
    Content-Type: Multipart/Mixed;
    	boundary=\"$sep\"
    
    charset=\"iso-8859-1\"
    Content-Transfer-Encoding: 7bit
    
    --$sep
    Content-Type: $mime_type;
    	name=\"$filename\"
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment;
    		filename=\"$filename\"
    		
    $fdata
    --$sep";
    
    
    $headers = str_replace("\n", "\r\n", $headers); 
    
    ...
    Yes, and also do what djones suggested.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •