< Back to Code Samples
<?php

require_once("upload.class");

/****************************************************************
*  [Email] Attachment class

*  PURPOSE: 
*    Used when you have a form that uploads a file which will be 
*    sent via email. This class will process each file (via its parent
*    class, above). It provides functions for base64 encoding and 
*    printing to MIME standards.
*
*  USAGE:
*    $myFiles = array();
*    foreach ($_FILES as $file) {
*        $uploadedFile = new Attachment($file);
*        array_push($myFiles, $uploadedFile);
*    }
*
*    [ ... Meanwhile, back in the email ... ]
*
*    foreach ($myFiles as $file) {
*        $body .= $file->toString(YOUR_MIME_BOUNDARY);
*        $body .= $file->encode();
*    }    
*
******************************************************************/

class Attachment extends Upload {
    var 
$type "application/octet-stream";
    
    function 
__construct($_file_array) {
        
parent::__construct($_file_array);
        
    }
    
    function 
__destruct() {
        if (
file_exists($this->temp $this->name)) 
            
unlink($this->temp $this->name);
    }


    
/**
    * encode returns the actual file attachment, encoded for brevity.
    * 
    * @return The file contents in base64.
    */
    
public function encode() {
        
$fh fopen($this->temp $this->name,'rb'); 
        
$data fread($fh,filesize($this->temp $this->name)); 
        
fclose($fh); 
        return 
chunk_split(base64_encode($data)) . "\n\n";
    }    


    
/**
    * toString returns a prepared string of the MIME information for the 
    * file. NOTE!!! You still need to call "encode()" to actually include
    * the file itself!
    *
    * @param     $mime_boundary Whatever you'd like it to be...
    * @return    The prepared text.
    */
    
public function toString($mime_boundary) {
        
$output "--{$mime_boundary}\n" 
                
"Content-Type: " $this->type ";\n" 
                
" name=\"" $this->name "\"\n" 
                
"Content-Transfer-Encoding: base64\n\n";
        return 
$output;
    }
    
}

?>