Jump to content
Larry Ullman's Book Forums
ianhg

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

<?php
include('includes/config3.php');
// 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.';
                break;
            case 2:
                print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
                break;
            case 3:
                print 'The file was only partially uploaded.';
                break;
            case 4:
                print 'No file was uploaded.';
                break;
            case 6:
                print 'No temporary folder was available.';
                break;
            case 7:
                print 'Unable to write to the disk.';
                break;
            case 8:
                print 'File upload stopped.';
                break;
            default:
                print 'A system error occurred.';
                break;
        } // 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)
      return'';
  }
  //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']) ) {
   }else{
          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']}
      \nTelephone:{$scrubbed['telephone']}
       \nMobile:{$scrubbed['mobile']}  
     \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>";
      

?>
 

Share this post


Link to post
Share on other sites

Hi

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.

Share this post


Link to post
Share on other sites

Here's another tutorial:

http://webcheatsheet.com/PHP/send_email_text_html_attachment.php

 

I guess you could use the temp file and attach that to the email, in the case that you don't want to refresh the page or whatever.

Personally, I think it better and safer to ensure a proper file upload before sending the file as an attachment though.

Share this post


Link to post
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?

Thanks

Share this post


Link to post
Share on other sites

As with any input received from a user, you always need to scrub and validate it thoroughly. So long as your sure that the user input is safe, you can use it.

Share this post


Link to post
Share on other sites

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

<?php
// 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";
$multipleUpload="yes";
?><?php
include('includes/config3.php');
// 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)
      return'';
  }
  //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
$ssAct=$_POST["ssAct"];

 

$ssSumMath=$_POST["ssSumMath"];
$ssMathTest=$_POST["ssMathTest"];
$ssName=$_POST["ssName"];
$ssEmail=$_POST["ssEmail"];
$ssPhone=$_POST["ssPhone"];
$ssMobile=$_POST["ssMobile"];
$ssHouse=$_POST["ssHouse"];
$ssZip=$_POST["ssZip"];
$ssReg=$_POST["ssReg"];
$ssMake=$_POST["ssMake"];
$ssModel=$_POST["ssModel"];
$ssMessage=$_POST["ssMessage"];
$ssFile=$_POST["ssFile"];

?>
 
 
 
 
<?php
// file type check - allowed png, gif, jpeg, jpg, rar, zip, pdf
if($ssAct!='')
{

// 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

        for($i=0;$i<count($_FILES['ssFile']['size']);$i++)
        {
            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
              )
                    {
                    $fileAllow="true";
                    $whichFile="all";
                    }
                else
                    {
                    $whichFile=$_FILES['ssFile']['type'][$i];
                    $fileAllow="false";
                    // if any disallowed file is trapped - block attachment and sending email - and show alert
                    break;
                    }
        }
}
?>
  <?php
if($ssSumMath!=$ssMathTest && $ssAct=='send') {
// Math test code wrong
$testSeries1="false";
}
//////////////////////
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>";
}
*/
?>
<?php
// 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>
    <div style='clear:both;'></div>
  </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>
    </div>
    <p><strong>Message Details:</strong></p>
   
    <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>
     <p><em>Damage to vehicle:</em>$ssMessage</p>
  </div>
</div>";

          // generate a random string to use as boundary marker
          $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
          // 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
          $message=$body;
          // 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
                if(is_uploaded_file($tmp_name))
                {
                   // 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
                   fclose($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
          $message.="--{$mime_boundary}--\n";
          // 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>";
          }
        else
            {
            $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>";
    
    
  ?></p>
 
Hope this might help someone else.

Share this post


Link to post
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]))) {
	    $fileAllow="true";
	}
	else {
	    $fileAllow="false";
	}
}

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.

Share this post


Link to post
Share on other sites

Many thanks for your advice and help.

ianhg,

Did you ever get this to work? If so, would you mind sharing the entire code? I'm know nothing about php, but i can certainly code the form page in html.

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...

×
×
  • Create New...