Jump to content
Larry Ullman's Book Forums

Uploading An Image From Web Form And Send As Email Attachement

Recommended Posts

Hi Guys

I have a contact form with the ability to upload an image and all is working ok. The contact form sends an email and currently uploads the image to the server.

What I want to do is attach the image to the email as well. Code below any guidance would be appreciated, thanks

// Check if the form has been submitted:
if (isset($_POST['submitted'])) {

    // Check for an uploaded file:
    if (isset($_FILES['photoTemp'])) {
        // Validate the type. Should be JPEG or PNG.
        $allowed = array ('image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png');
        if (in_array($_FILES['photoTemp']['type'], $allowed)) {
            // Move the file over.
            if (move_uploaded_file ($_FILES['photoTemp']['tmp_name'], "/var/www/vhosts/xxxxx/httpdocs/photoTemp/{$_FILES['photoTemp']['name']}")) {
                echo '<p><em>The file has been uploaded!</em></p>';
            } // End of move... IF.
        } else { // Invalid type.
            echo '<p class="error">Please upload a JPEG or PNG image.</p>';

    } // End of isset($_FILES['upload']) IF.
    // Check for an error:
    if ($_FILES['photoTemp']['error'] > 0) {
        echo '<p class="error">The file could not be uploaded because: <strong>';
        // Print a message based upon the error.
        switch ($_FILES['photoTemp']['error']) {
            case 1:
                print 'The file exceeds the upload_max_filesize setting in php.ini.';
            case 2:
                print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
            case 3:
                print 'The file was only partially uploaded.';
            case 4:
                print 'No file was uploaded.';
            case 6:
                print 'No temporary folder was available.';
            case 7:
                print 'Unable to write to the disk.';
            case 8:
                print 'File upload stopped.';
                print 'A system error occurred.';
        } // End of switch.
        print '</strong></p>';
    } // End of error IF.
    // Delete the file if it still exists:
    if (file_exists ($_FILES['photoTemp']['tmp_name']) && is_file($_FILES['photoTemp']['tmp_name']) ) {
        unlink ($_FILES['photoTemp']['tmp_name']);
} // End of the submitted conditional.
 function spam_scrubber($value)
     //list of bad values
      $very_bad = array('to:','cc:','bcc:','content-type:','mime-version:','multipart-mixed:','content-transfer-encoding:');
 //if any of the bad strings are in submitted value return an empty string
 foreach ($very_bad as $v)
     if (stripos($value, $v) !== false)
  //replace any newline chara with spaces
  $value = str_replace(array("\r","\n","%0a","%0d"), ' ',$value);
 return trim($value);
 //end of spam scrubber function
 //clean form data
 $scrubbed = array_map('spam_scrubber',$_POST);
 // form validation
  if (!empty($scrubbed['name'])&&!empty($scrubbed['email'])&&!empty($scrubbed['telephone'])&&!empty($scrubbed['post_code'])&&!empty($scrubbed['car_reg']) ) {
          echo "<h3>Sorry. You did not properly fill out the form. Please try again./</h3>";
     //create body
     $body =  "Quote for damage required\nCustomer Vehicle Details\n
      \nCustomers Name: {$scrubbed['name']}
     \ne-mail address:{$scrubbed['email']}
      \nConfirmed email:{$scrubbed['confirm_email']}
     \nCustomers Address:{$scrubbed['adress']}
   \nPost Code:{$scrubbed['post_code']}
  \nCar Registration:{$scrubbed['car_reg'] }
 \nCar Make: {$scrubbed['car_make' ] }
  \nCar Model: {$scrubbed['car_model']}
        \nDetails of Damage:{$scrubbed['damage']}
     \nPhoto of Damage:{$scrubbed['photoTemp']}";
     // $photoTemp->addAttachment($path_of_uploaded_file);
  $body = wordwrap($body, 180);
 //    $mail_body = '
 mail($mailuser,'Quote for damage repair from website',$body, "From:<".$mailuser.">");

    // *** This is where you would post a comment to inform visitor of the data sent, etc ***
     echo "<p>You information input has been sent <br><br>";
     echo "This is what you sent  <br><br>";
       echo "Your Name:\"" .$scrubbed["name"] ."\" <br>";
      echo "Your email:\"" .$scrubbed["email"] ."\" <br>";
  echo "Confirmed email:\"" .$scrubbed["confirm_email"] ."\" <br>";
      echo "Your Telephone number:\"".$scrubbed["telephone"]."\"<br>";
      echo "Your Mobile number:\"".$scrubbed["mobile"]."\"<br>";
      echo"Your House name or Number:\"".$scrubbed["address"]."\"<br>";
      echo "Your Postal Code:\"".$scrubbed["post_code"]."\"<br>";
      echo "Your Vehicle Reg:\"" .$scrubbed["car_reg"] ."\" <br>";
        echo "Your Vehicle Make: \"" . $scrubbed["car_make"] . "\" <br>";
      echo "Your Vehicle Model: \"" . $scrubbed["car_model"] . "\" <br>";
      echo "The damage to vehicle: \"" .$scrubbed["damage"] . "\" <br></p>";


Link to comment
Share on other sites


Thanks for the speedy reply margaux and the link, but I was hoping to find a way of adding to the existing script rather than start afresh. But then again maybe I need to, thanks.

Link to comment
Share on other sites

Thanks for the link HartleySan.

I am saving the images to the server but would like the image to be sent as an attachment with email using hopefully the above code. But concerned about the link as I thought that headers were a risky for header injection and automated submission?


Link to comment
Share on other sites

  • 2 weeks later...

Just thought I would share this, I struggled to get this working but have now succeeded.

// Settings
@ini_set('max_execution_time', "30"); // 30 seconds
// print ini_get('max_execution_time');
@ini_set('memory_limit', "64M"); // 8MB - Set any from 8M, 16M, 24M, 32M, 40M, 48M, 56M, 64M, 128M
// print ini_get('memory_limit');

// these two below are best to adjust via .htaccess - see documentation
@ini_set('post_max_size', "2M"); // 10MB
@ini_set('upload_max_filesize', "2M"); // 10MB

// Max File Size Allowed - Soft Restriction - Not always fool proof but its better to use
$Max_File_Size="1048576"; // In bytes - 10485760=10MB, 4194304=4MB, 2097152=2MB, 1048576=1MB

// print ini_get('post_max_size');

// allow multiple upload or single upload
// set this no to allow single upload - use lowercase
// $multipleUpload="no";
// Check if the form has been submitted:
if (isset($_POST['submitted']));
 function spam_scrubber($value)
     //list of bad values
      $very_bad = array('cc:','bcc:','content-type:','mime-version:','multipart-mixed:','content-transfer-encoding:');
 //if any of the bad strings are in submitted value return an empty string
 foreach ($very_bad as $v)
     if (stripos($value, $v) !== false)
  //replace any newline chara with spaces
  $value = str_replace(array("\r","\n","%0a","%0d"), ' ',$value);
 return trim($value);

 //end of spam scrubber function
// get all post data



// file type check - allowed png, gif, jpeg, jpg, rar, zip, pdf

// view array - for testinf
// print_r( $_FILES );

// add this one line below if rar is not being accepted in system
// || strstr($_FILES['ssFile']['type'][$i], 'application/rar')!==false

// allow psd - add below if you want to allow psd files
// || strstr($_FILES['ssFile']['type'][$i], 'application/photoshop')!==false

            if(strstr($_FILES['ssFile']['type'][$i], 'image/png')!==false
                 || strstr($_FILES['ssFile']['type'][$i], 'image/jpg')!==false
                || strstr($_FILES['ssFile']['type'][$i], 'image/jpeg')!==false
                || strstr($_FILES['ssFile']['type'][$i], 'image/pjpeg')!==false
                //|| strstr($_FILES['ssFile']['type'][$i], 'application/x-rar-compressed')!==false
                //|| strstr($_FILES['ssFile']['type'][$i], 'application/zip')!==false
                //|| strstr($_FILES['ssFile']['type'][$i], 'application/pdf')!==false
                    // if any disallowed file is trapped - block attachment and sending email - and show alert
if($ssSumMath!=$ssMathTest && $ssAct=='send') {
// Math test code wrong
if($testSeries1=='false') {
echo "<div class='alert alert-error'><p><strong>Simple math test verification failed</strong>! Please try again! Please click your back button in your browser.</p></div>";
if($fileAllow=='false' && $whichFile!='') {
echo "<div class='alert alert-error'><p><strong>File Type</strong> [<strong> $whichFile </strong>] is not allowed! Only JPG, JPEG, PNG, are allowed. Please try again! Please click your back button in your browser.</p></div>";
if($whichFile=='' && $ssAct=='send') {
echo "<div class='alert alert-info'>This is just an info! You did not attach any file!</div>";
// send email
if($ssAct!='' && $ssAct=='send' && $testSeries1!='false' && $fileAllow!='false' || $ssAct!='' && $ssAct=='send' && $testSeries1!='false' && $fileAllow=='false' && $whichFile=='')
       // attach files and send html email ////////////////////////////////////////////////////////////////

       // where email should go
       $to= $mailuser;
       // email subject
       $subject="Small Damage Quote Required Email from website " .$mailuser;
       // sender email
       $from = $mailuser;

       $body = "<div style='background-color:#F4F4F4;padding:10px 0;font-family:Helvetica,Arial,sans-serif;' align='center'>
<div style='width:600px;border:1px solid #DBDBDB;border-radius:6px;background-color:#fff;'>
  <div style='background-color:#2664B1;height:100px;border-radius:6px 6px 0 0;box-shadow:0px 0px 10px 0px #ccc;border-bottom:1px solid #1067A0;'>
    <div style='float:left;' align='left'>
      <div style='color:#fff;font-size:25px;font-weight:bold;padding:24px 0 0 20px;text-shadow:2px 1px 1px #0B456C;'>Damage Quote Required enquiry from website.</div>
      <div style='color:#D7ECFB;padding:0 0 0 20px; font-size:14px;text-shadow:1px 1px 1px #0B456C;'>Request for quote</div>
      <div style='clear:both;'></div>
    <div style='clear:both;'></div>
  <div align='left' style='padding:10px 30px; text-align:justify; color:#666; font-size:13px;line-height:22px;'>
    <div style='border-bottom:1px solid #eee;margin:10px 0;'>
      <p>You have received a message from <br /><strong>$ssName [ $ssEmail ]</strong></p>
    <p><strong>Message Details:</strong></p>
    <em>Name:</em>$ssName<br />
    <em>email address:</em>$ssEmail<br />
    <em>Phone No:</em> $ssPhone<br />
      <em>Mobile No:</em> $ssMobile<br />
      <em>House Name or Number:</em> $ssHouse<br />
       <em>Post Code:</em> $ssZip<br />
      <em>Car Registration:</em> $ssReg <br/>
      <em>Car Model:</em>$ssModel<br/>
     <p><em>Damage to vehicle:</em>$ssMessage</p>

          // generate a random string to use as boundary marker
          // email headers

          $headers = "From: $mailuser\r\n" .
          "Reply-To: $mailuser\r\n" .
          "Return-Path: $mailuser\r\n" .
          "MIME-Version: 1.0\r\n" .
             "Content-Type: multipart/mixed;\r\n" .
             " boundary=\"{$mime_boundary}\"";

          // text message to display in email
          // MIME boundary for email message
          $message = "This is a multi-part message in MIME format.\n\n" .
             "--{$mime_boundary}\n" .
             "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
             "Content-Transfer-Encoding: 7bit\n\n" .
          $message . "\n\n";

    // get uploaded files from form in loop
    function reArrayFiles($ssFile)
        $file_ary = array();
        $file_count = count($ssFile['name']);
        $file_keys = array_keys($ssFile);
            for ($i=0; $i<$file_count; $i++)
                foreach ($file_keys as $key)
                    $file_ary[$i][$key] = $ssFile[$key][$i];
       return $file_ary;
           $file_ary = reArrayFiles($_FILES['ssFile']);
          // process files
          foreach($file_ary as $file)
             // store file information in variables
             $tmp_name = $file['tmp_name'];
             $type = $file['type'];
             $name = $file['name'];
             $size = $file['size'];
             // echo $tmp_name."\n\n";
             // if file exists
             if (file_exists($tmp_name))
                // check to make sure it is uploaded file - not a system file
                   // open file for a binary read
                   $file = fopen($tmp_name,'rb');
                   // read file content into a variable
                   $data = fread($file,filesize($tmp_name));
                   // close file
                   // encode it and split it into acceptable length lines
                   $data = chunk_split(base64_encode($data));

                // insert a boundary to start the attachment
                // specify the content type, file name, and disposition
                // boundary between each file
                $message .= "--{$mime_boundary}\n" .
                   "Content-Type: {$type};\n" .
                   " name=\"{$name}\"\n" .
                   "Content-Disposition: attachment;\n" .
                   " filename=\"{$name}\"\n" .
                   "Content-Transfer-Encoding: base64\n\n" .
                $data . "\n\n";
          // closing mime boundary - end of message
          // send email
          if (@mail($to, $subject, $message, $headers))
              if($ssCopyEmail=='No') { @mail($ssEmail, $subject, $message, $headers); }
          $sentMessage="<p>Email sent. Thank you. We will contact you within 48 hours.</p>";
            $sentError="<p>Sorry the Email was not sent due to some error</p>";

  <?php if($sentMessage!='') { ?>
  <div class="alert alert-success"><?php echo "$sentMessage"; ?></div>
  <?php } ?>
  <?php if($sentError!='') { ?>
  <div class="alert alert-error"><?php echo "$sentError"; ?></div>
  <?php } ?><br>
 <p> <?php
   echo "Your information input has been sent <br><br>";
     echo "This is what you sent  <br>";
      echo "Your Details:<br><br>";
     echo "Your Name:\"".$_POST["ssName"]."\"<br>";
     echo "Your email:\"".$_POST["ssEmail"]."\"<br>";
     echo "Home Tel No:\"".$_POST["ssPhone"]."\"<br>";
      echo "Mobile Tel No:\"".$_POST["ssMobile"]."\"<br>";
      echo "Your House Name or Number:\"">$_POST["ssHouse"]."\"<br>";
      echo "Post Code:\"" .$_POST["ssZip"] . "\"<br>";    
     echo "Your Vehicle Details<br><br>";
     echo "Vehicle Registration No: \"" .$_POST["ssReg"] . "\" <br>";
      echo  "Vehicle Make:\"".$_POST["ssMake"]. "\" <br>";
     echo "Vehicle Model:\"".$_POST["ssModel"]."\"<br>";    
     echo "Brief Details of Damage:\"".$_POST["ssMessage"]."\"<br>";
Hope this might help someone else.

Link to comment
Share on other sites

@ianhg, that's great that you got it to work. Whilst there is nothing wrong with your code, I hope you don't mind if I make a couple of suggestions.


As is, it won't be easy to maintain so you might want to consider making it more modulable (probably not a word but I'm sure you know what I mean). You could put your functions in a separate file, say functions.php and include that file.


To check for allowed file types - put all the allowed file types into an array, then use the function in_array() to see if the file type is in the array. If you need to allow or disallow a filetype, just add/remove it from the array. Here's a function I created

function file_allowed($filetype) {
$filesAllowed = array('image/png','image/jpg','image/jpeg','image/pjpeg','application/x-rar-compressed','application/zip','application/pdf');
	if (in_array($filetype, $filesAllowed)) {
		return true;
	else {
		return false;

Then when you loop through $_FILES, you could replace all that awkward code with

$count = count($_FILES['ssFile']['size']) 
for ($i=0; $i<$count; $i++) {
	if (file_allowed(strstr($_FILES['ssFile']['type'][$i]))) {
	else {

Note - I created a count variable so you only count through the $_FILES array once, not every time you run through the loop. For big loops this will help with performance.


I'm not sure $_FILES{'type'] is the best way to access the file type as it is supplied by the browser and can be manipulated. You might want to parse the file name instead.


Hope this helps.

Link to comment
Share on other sites

  • 1 year later...

  • Create New...