Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add Attachments Option to Email Form 1

Status
Not open for further replies.

MrTBC

Technical User
Nov 19, 2003
610
US
Hi guys.
I'm a total PHP newbie and would really appreciate some help with this.

I would like to edit the code shown below which sends an email so that the user can add a file attachment. The user needs to be able to browse and select this from their c drive. The attachment does not need to be saved after it has been sent.

Preferably users would also be restricted to only using .doc and .pdf format attachments.

OK, here's the code.

Thanks very much.

1. CONTACT.PHP

Code:
<?
session_start();
include_once("admin/inc.php");
$tplContact=new TplLoad;
$tplContact->assign("phpself",$_SERVER['PHP_SELF']);
if ($set_contact_login_need)
	check_valid_user("");

// Refereer information
$legal = 0;
$lServerRef = explode("/",getenv("HTTP_REFERER"));
$lUserid=getParam("user_id","");
$tplContact->assign("ad_owner",getParam("ad_owner",""));
$tplContact->assign("id",getParam("id",""));
$tplContact->assign("user_id",getParam("user_id",""));
if ($set_img_validation==1)
		$tplContact->assign("image_validation",1);

if (getParam("submit",""))
{
		$errorStr="";
		
		$tplContact->assign("contact_name",getParam("contact_name",""));
		$tplContact->assign("contact_email",getParam("contact_email",""));
		$tplContact->assign("contact_message",strip_tags(getParam("contact_message","")));
		
		if (empty($lUserid))
			$errorStr.="<li>".LA_ERROR_MSG5."</li>";
			
		if (!validEmail(getParam("contact_email","")))
			$errorStr.="<li>".LA_ERROR_MSG21."</li>";
			
		if (getParam("contact_email","")=="")
			$errorStr.="<li>".LA_ERROR_MSG8."</li>";	
			
		if (getParam("contact_name","")=="")
			$errorStr.="<li>".LA_ERROR_MSG5."</li>";	
			
		if (!empty($set_ref) && !eregi("$set_ref",".$lServerRef[2]."))
			$errorStr.="<li>".LA_REF_FAILED."</li>";	
			
		if (getParam("contact_message","")=="")
			$errorStr.="<li>".LA_ERROR_MSG88."</li>";	
			
		if ($_SESSION["validate_sign_session"] <> $_REQUEST["validate_sign"] && $set_img_validation)		
			$errorStr.="<li>".LA_IMG_VER_FAILED."</li>";
		
		
		if (empty($errorStr))
		{
			$sql = "select ad_owner,user_name,user_email from $ads_tbl,$usr_tbl where ad_owner=user_id AND user_id = $lUserid limit 1";
 			$sql_resultads = q($sql);
			$row=mysql_fetch_array($sql_resultads);
			$lRecieveEmail = $row["user_email"];
			$lRecieveName = $row["user_name"];
			
			$lContactMessage=strip_tags(getParam("contact_message",""));
		 	$lContactName=strip_tags(getParam("contact_name",""));
		 	$lContactEmail=strip_tags(getParam("contact_email",""));
		 	
		 	$sql="select ad_title,ad_id from $ads_tbl where ad_id='".getParam("id","")."'";
		 	$res_title=q($sql);
		 	$row_title=mysql_fetch_array($res_title);
		 	$lAdTitle=$row_title["ad_title"];
		 	
		 	$lAdID=$row_title["ad_id"];
		 	
		  	$lEmailBody=formatString(LA_EMAIL_BODY,array(getParam("ad_owner",""),"$lContactName","$lContactMessage","$lContactEmail",getRemoteIp(),"$lAdTitle","$lAdID","$name_of_site","$url"));
		  	$lEmailTitle=formatString(LA_EMAIL,array(getParam("ad_owner",""),"$lContactName","$lContactMessage","$lContactEmail",getRemoteIp(),"$lAdTitle","$lAdID","$name_of_site","$url"));
		  	
		  	$tplContact->assign("message_sent",formatString(LA_SENT_MESSAGE,array("$lRecieveName")));
			sendEmail($lRecieveEmail,$lContactEmail,$lEmailTitle,$lEmailBody);
			$tplContact->assign("contact_ok",1);
			$sql_2 = "update $usr_tbl set user_contacted = user_contacted + 1 where user_id = $lUserid";
			$sql_resultupd = q ($sql_2);
			addToHistory(2,$lUserid,"","");
			
		}
		else 
		{	
			$tplContact->assign("contact_fail",$errorStr);
		}	
		
		}
		
	else
	{
	
	$sql_eier = "select user_name from $usr_tbl where user_id = $lUserid";
	$result = q ($sql_eier);
	$row_contact = mysql_fetch_array($result);
	$tplContact->assign("ad_owner",$row_contact["user_name"]);
	$tplContact->assign("contact_name",$_SESSION["user_name"]);
	$tplContact->assign("contact_email", $_SESSION["user_email"]);
}
$tplContact->display("contact.tpl");
?>

--------------------------------------------

2. CONTACT.TPL

Code:
<table class="box"><tr><th>{$smarty.const.LA_KONTAKT}</th></tr><td>
<h2>{$smarty.const.LA_KONTAKT}</h2>

{if $contact_ok}
  {$message_sent}
{else}


<form method="post" action="{$phpself}" name="itemForm" id="itemForm">

<input type="hidden" name="ad_owner" value="{$ad_owner}">
<input type="hidden" name="user_id" value="{$user_id}">
<input type="hidden" name="id" value="{$id}">
<input type="hidden" name="contact" value="1">
		
<!-- t1 -->
{$smarty.const.LA_MAIN_MESSAGE} <b>{$ad_owner}</b>.<br />

  
  	{if $contact_fail}
		<ol class="red"> {$contact_fail} </ol>
	{/if}
  
  
<!-- t3 -->
<table border="0" cellspacing="1">
<tr>
  <td width="50%" valign="top"> {$smarty.const.ADD_USER_NAME} </td>
  <td width="50%" valign="top"> <input type="text" name="contact_name" value="{$contact_name}" size="35" > </td>
</tr>
<tr>
  <td width="50%" valign="top"> {$smarty.const.ADD_USER_EMAIL} </td>
  <td width="50%" valign="top"> <input type="text" name="contact_email" value="{$contact_email}" size="35" > </td>
</tr>
<tr>
  <td width="50%" valign="top"> {$smarty.const.LA_CONTACT_MSG} </td>
  <td width="50%" valign="top"><textarea rows="5" name="contact_message" cols="27" rows="10">{$contact_message}</textarea></td>
</tr>

{if $image_validation}
   <tr>
     <td> {$smarty.const.LA_IMG_VER}:</td>
     <td valign="top" class="star"><img src="val_img.php" alt="" /></td></tr>
    
     
    <tr>
     <td> {$smarty.const.LA_IMG_VER2}:</td>
     <td valign="top" class="star">
     <input type="text" class="txt" name="validate_sign" size="16" maxlength="16" /> *</td></tr>
{/if}
</table>


<input type="submit" value="{$smarty.const.LA_KONTAKT}" name="submit" class="button" />
</form>
{/if}

<p>&nbsp;</p>

</td></tr></table>


{literal}
<script language="javascript" type="text/javascript">
<!--
content=document.getElementById("contact_name");
if( content != null ){content.focus();}
-->
</script>
{/literal}
 
i'm not sure whether it's worth trying to adapt this code. not because it's bad - just that it appears to be linked into a templating system and making changes might cock up other bits; or conversely, to do it properly, you'd want to extend the base template.

are you able to start from the ground up or MUST you use this script?
 
Hi jpadie.
Thanks for your reply. Yes, I must use this script I'm afraid.

Thanks.
 
This appears to be what it uses, htmlMimeMail,:

Code:
<?php
/**
* This file is part of the htmlMimeMail package ([URL unfurl="true"]http://www.phpguru.org/)[/URL]
*
* htmlMimeMail is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* htmlMimeMail is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with htmlMimeMail; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
* 
* © Copyright 2004 Richard Heyes
*/

require_once(dirname(__FILE__) . '/mimePart.php');

class htmlMimeMail
{
    /**
    * The html part of the message
    * @var string
    */
    var $html;

    /**
    * The text part of the message(only used in TEXT only messages)
    * @var string
    */
    var $text;

    /**
    * The main body of the message after building
    * @var string
    */
    var $output;

    /**
    * The alternative text to the HTML part (only used in HTML messages)
    * @var string
    */
    var $html_text;

    /**
    * An array of embedded images/objects
    * @var array
    */
    var $html_images;

    /**
    * An array of recognised image types for the findHtmlImages() method
    * @var array
    */
    var $image_types;

    /**
    * Parameters that affect the build process
    * @var array
    */
    var $build_params;

    /**
    * Array of attachments
    * @var array
    */
    var $attachments;

    /**
    * The main message headers
    * @var array
    */
    var $headers;

    /**
    * Whether the message has been built or not
    * @var boolean
    */
    var $is_built;
    
    /**
    * The return path address. If not set the From:
    * address is used instead
    * @var string
    */
    var $return_path;
    
    /**
    * Array of information needed for smtp sending
    * @var array
    */
    var $smtp_params;

    /**
    * Constructor function. Sets the headers
    * if supplied.
    */
    function htmlMimeMail()
    {
        /**
        * Initialise some variables.
        */
        $this->html_images = array();
        $this->headers     = array();
        $this->is_built    = false;

        /**
        * If you want the auto load functionality
        * to find other image/file types, add the
        * extension and content type here.
        */
        $this->image_types = array(
                                    'gif'	=> 'image/gif',
                                    'jpg'	=> 'image/jpeg',
                                    'jpeg'	=> 'image/jpeg',
                                    'jpe'	=> 'image/jpeg',
                                    'bmp'	=> 'image/bmp',
                                    'png'	=> 'image/png',
                                    'tif'	=> 'image/tiff',
                                    'tiff'	=> 'image/tiff',
                                    'swf'	=> 'application/x-shockwave-flash'
                                  );

        /**
        * Set these up
        */
        $this->build_params['html_encoding'] = 'quoted-printable';
        $this->build_params['text_encoding'] = '7bit';
        $this->build_params['html_charset']  = 'ISO-8859-1';
        $this->build_params['text_charset']  = 'ISO-8859-1';
        $this->build_params['head_charset']  = 'ISO-8859-1';
        $this->build_params['text_wrap']     = 998;

        /**
        * Defaults for smtp sending
        */
        if (!empty($GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'])) {
            $helo = $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'];
        } elseif (!empty($GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME'])) {
            $helo = $GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME'];
        } else {
            $helo = 'localhost';
        }

        $this->smtp_params['host'] = 'localhost';
        $this->smtp_params['port'] = 25;
        $this->smtp_params['helo'] = $helo;
        $this->smtp_params['auth'] = false;
        $this->smtp_params['user'] = '';
        $this->smtp_params['pass'] = '';

        /**
        * Make sure the MIME version header is first.
        */
        $this->headers['MIME-Version'] = '1.0';
    }

    /**
    * This function will read a file in
    * from a supplied filename and return
    * it. This can then be given as the first
    * argument of the the functions
    * add_html_image() or add_attachment().
    */
    function getFile($filename)
    {
        $return = '';
        if ($fp = fopen($filename, 'rb')) {
            while (!feof($fp)) {
                $return .= fread($fp, 1024);
            }
            fclose($fp);
            return $return;

        } else {
            return false;
        }
    }

    /**
    * Accessor to set the CRLF style
    */
    function setCrlf($crlf = "\n")
    {
        if (!defined('CRLF')) {
            define('CRLF', $crlf, true);
        }

        if (!defined('MAIL_MIMEPART_CRLF')) {
            define('MAIL_MIMEPART_CRLF', $crlf, true);
        }
    }

    /**
    * Accessor to set the SMTP parameters
    */
    function setSMTPParams($host = null, $port = null, $helo = null, $auth = null, $user = null, $pass = null)
    {
        if (!is_null($host)) $this->smtp_params['host'] = $host;
        if (!is_null($port)) $this->smtp_params['port'] = $port;
        if (!is_null($helo)) $this->smtp_params['helo'] = $helo;
        if (!is_null($auth)) $this->smtp_params['auth'] = $auth;
        if (!is_null($user)) $this->smtp_params['user'] = $user;
        if (!is_null($pass)) $this->smtp_params['pass'] = $pass;
    }

    /**
    * Accessor function to set the text encoding
    */
    function setTextEncoding($encoding = '7bit')
    {
        $this->build_params['text_encoding'] = $encoding;
    }

    /**
    * Accessor function to set the HTML encoding
    */
    function setHtmlEncoding($encoding = 'quoted-printable')
    {
        $this->build_params['html_encoding'] = $encoding;
    }

    /**
    * Accessor function to set the text charset
    */
    function setTextCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['text_charset'] = $charset;
    }

    /**
    * Accessor function to set the HTML charset
    */
    function setHtmlCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['html_charset'] = $charset;
    }

    /**
    * Accessor function to set the header encoding charset
    */
    function setHeadCharset($charset = 'ISO-8859-1')
    {
        $this->build_params['head_charset'] = $charset;
    }

    /**
    * Accessor function to set the text wrap count
    */
    function setTextWrap($count = 998)
    {
        $this->build_params['text_wrap'] = $count;
    }

    /**
    * Accessor to set a header
    */
    function setHeader($name, $value)
    {
        $this->headers[$name] = $value;
    }

    /**
    * Accessor to add a Subject: header
    */
    function setSubject($subject)
    {
        $this->headers['Subject'] = $subject;
    }

    /**
    * Accessor to add a From: header
    */
    function setFrom($from)
    {
        $this->headers['From'] = $from;
    }

    /**
    * Accessor to set the return path
    */
    function setReturnPath($return_path)
    {
        $this->return_path = $return_path;
    }

    /**
    * Accessor to add a Cc: header
    */
    function setCc($cc)
    {
        $this->headers['Cc'] = $cc;
    }

    /**
    * Accessor to add a Bcc: header
    */
    function setBcc($bcc)
    {
        $this->headers['Bcc'] = $bcc;
    }

    /**
    * Adds plain text. Use this function
    * when NOT sending html email
    */
    function setText($text = '')
    {
        $this->text = $text;
    }

    /**
    * Adds a html part to the mail.
    * Also replaces image names with
    * content-id's.
    */
    function setHtml($html, $text = null, $images_dir = null)
    {
        $this->html      = $html;
        $this->html_text = $text;

        if (isset($images_dir)) {
            $this->_findHtmlImages($images_dir);
        }
    }

    /**
    * Function for extracting images from
    * html source. This function will look
    * through the html code supplied by add_html()
    * and find any file that ends in one of the
    * extensions defined in $obj->image_types.
    * If the file exists it will read it in and
    * embed it, (not an attachment).
    *
    * @author Dan Allen
    */
    function _findHtmlImages($images_dir)
    {
        // Build the list of image extensions
        while (list($key,) = each($this->image_types)) {
            $extensions[] = $key;
        }

        preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $images);

        for ($i=0; $i<count($images[1]); $i++) {
            if (file_exists($images_dir . $images[1][$i])) {
                $html_images[] = $images[1][$i];
                $this->html = str_replace($images[1][$i], basename($images[1][$i]), $this->html);
            }
        }

        if (!empty($html_images)) {

            // If duplicate images are embedded, they may show up as attachments, so remove them.
            $html_images = array_unique($html_images);
            sort($html_images);
    
            for ($i=0; $i<count($html_images); $i++) {
                if ($image = $this->getFile($images_dir.$html_images[$i])) {
                    $ext = substr($html_images[$i], strrpos($html_images[$i], '.') + 1);
                    $content_type = $this->image_types[strtolower($ext)];
                    $this->addHtmlImage($image, basename($html_images[$i]), $content_type);
                }
            }
        }
    }

    /**
    * Adds an image to the list of embedded
    * images.
    */
    function addHtmlImage($file, $name = '', $c_type='application/octet-stream')
    {
        $this->html_images[] = array(
                                        'body'   => $file,
                                        'name'   => $name,
                                        'c_type' => $c_type,
                                        'cid'    => md5(uniqid(time()))
                                    );
    }


    /**
    * Adds a file to the list of attachments.
    */
    function addAttachment($file, $name = '', $c_type='application/octet-stream', $encoding = 'base64')
    {
        $this->attachments[] = array(
                                    'body'		=> $file,
                                    'name'		=> $name,
                                    'c_type'	=> $c_type,
                                    'encoding'	=> $encoding
                                  );
    }

    /**
    * Adds a text subpart to a mime_part object
    */
    function &_addTextPart(&$obj, $text)
    {
        $params['content_type'] = 'text/plain';
        $params['encoding']     = $this->build_params['text_encoding'];
        $params['charset']      = $this->build_params['text_charset'];
        if (is_object($obj)) {
            $return = $obj->addSubpart($text, $params);
        } else {
            $return = new Mail_mimePart($text, $params);
        }
        
        return $return;
    }

    /**
    * Adds a html subpart to a mime_part object
    */
    function &_addHtmlPart(&$obj)
    {
        $params['content_type'] = 'text/html';
        $params['encoding']     = $this->build_params['html_encoding'];
        $params['charset']      = $this->build_params['html_charset'];
        if (is_object($obj)) {
            $return = $obj->addSubpart($this->html, $params);
        } else {
            $return = new Mail_mimePart($this->html, $params);
        }
        
        return $return;
    }

    /**
    * Starts a message with a mixed part
    */
    function &_addMixedPart()
    {
        $params['content_type'] = 'multipart/mixed';
        $return = new Mail_mimePart('', $params);
        
        return $return;
    }

    /**
    * Adds an alternative part to a mime_part object
    */
    function &_addAlternativePart(&$obj)
    {
        $params['content_type'] = 'multipart/alternative';
        if (is_object($obj)) {
            $return = $obj->addSubpart('', $params);
        } else {
            $return = new Mail_mimePart('', $params);
        }
        
        return $return;
    }

    /**
    * Adds a html subpart to a mime_part object
    */
    function &_addRelatedPart(&$obj)
    {
        $params['content_type'] = 'multipart/related';
        if (is_object($obj)) {
            $return = $obj->addSubpart('', $params);
        } else {
            $return = new Mail_mimePart('', $params);
        }
        
        return $return;
    }

    /**
    * Adds an html image subpart to a mime_part object
    */
    function _addHtmlImagePart(&$obj, $value)
    {
        $params['content_type'] = $value['c_type'];
        $params['encoding']     = 'base64';
        $params['disposition']  = 'inline';
        $params['dfilename']    = $value['name'];
        $params['cid']          = $value['cid'];
        $obj->addSubpart($value['body'], $params);
    }

    /**
    * Adds an attachment subpart to a mime_part object
    */
    function _addAttachmentPart(&$obj, $value)
    {
        $params['content_type'] = $value['c_type'];
        $params['encoding']     = $value['encoding'];
        $params['disposition']  = 'attachment';
        $params['dfilename']    = $value['name'];
        $obj->addSubpart($value['body'], $params);
    }

    /**
    * Builds the multipart message from the
    * list ($this->_parts). $params is an
    * array of parameters that shape the building
    * of the message. Currently supported are:
    *
    * $params['html_encoding'] - The type of encoding to use on html. ad_is_validated options are
    *                            "7bit", "quoted-printable" or "base64" (all without quotes).
    *                            7bit is EXPRESSLY NOT RECOMMENDED. Default is quoted-printable
    * $params['text_encoding'] - The type of encoding to use on plain text ad_is_validated options are
    *                            "7bit", "quoted-printable" or "base64" (all without quotes).
    *                            Default is 7bit
    * $params['text_wrap']     - The character count at which to wrap 7bit encoded data.
    *                            Default this is 998.
    * $params['html_charset']  - The character set to use for a html section.
    *                            Default is ISO-8859-1
    * $params['text_charset']  - The character set to use for a text section.
    *                          - Default is ISO-8859-1
    * $params['head_charset']  - The character set to use for header encoding should it be needed.
    *                          - Default is ISO-8859-1
    */
    function buildMessage($params = array())
    {
        if (!empty($params)) {
            while (list($key, $value) = each($params)) {
                $this->build_params[$key] = $value;
            }
        }

        if (!empty($this->html_images)) {
            foreach ($this->html_images as $value) {
                $this->html = str_replace($value['name'], 'cid:'.$value['cid'], $this->html);
            }
        }

        $null        = null;
        $attachments = !empty($this->attachments) ? true : false;
        $html_images = !empty($this->html_images) ? true : false;
        $html        = !empty($this->html)        ? true : false;
        $text        = isset($this->text)         ? true : false;

        switch (true) {
            case $text AND !$attachments:
                $message = &$this->_addTextPart($null, $this->text);
                break;

            case !$text AND $attachments AND !$html:
                $message = &$this->_addMixedPart();

                for ($i=0; $i<count($this->attachments); $i++) {
                    $this->_addAttachmentPart($message, $this->attachments[$i]);
                }
                break;

            case $text AND $attachments:
                $message = &$this->_addMixedPart();
                $this->_addTextPart($message, $this->text);

                for ($i=0; $i<count($this->attachments); $i++) {
                    $this->_addAttachmentPart($message, $this->attachments[$i]);
                }
                break;

            case $html AND !$attachments AND !$html_images:
                if (!is_null($this->html_text)) {
                    $message = &$this->_addAlternativePart($null);
                    $this->_addTextPart($message, $this->html_text);
                    $this->_addHtmlPart($message);
                } else {
                    $message = &$this->_addHtmlPart($null);
                }
                break;

            case $html AND !$attachments AND $html_images:
                if (!is_null($this->html_text)) {
                    $message = &$this->_addAlternativePart($null);
                    $this->_addTextPart($message, $this->html_text);
                    $related = &$this->_addRelatedPart($message);
                } else {
                    $message = &$this->_addRelatedPart($null);
                    $related = &$message;
                }
                $this->_addHtmlPart($related);
                for ($i=0; $i<count($this->html_images); $i++) {
                    $this->_addHtmlImagePart($related, $this->html_images[$i]);
                }
                break;

            case $html AND $attachments AND !$html_images:
                $message = &$this->_addMixedPart();
                if (!is_null($this->html_text)) {
                    $alt = &$this->_addAlternativePart($message);
                    $this->_addTextPart($alt, $this->html_text);
                    $this->_addHtmlPart($alt);
                } else {
                    $this->_addHtmlPart($message);
                }
                for ($i=0; $i<count($this->attachments); $i++) {
                    $this->_addAttachmentPart($message, $this->attachments[$i]);
                }
                break;

            case $html AND $attachments AND $html_images:
                $message = &$this->_addMixedPart();
                if (!is_null($this->html_text)) {
                    $alt = &$this->_addAlternativePart($message);
                    $this->_addTextPart($alt, $this->html_text);
                    $rel = &$this->_addRelatedPart($alt);
                } else {
                    $rel = &$this->_addRelatedPart($message);
                }
                $this->_addHtmlPart($rel);
                for ($i=0; $i<count($this->html_images); $i++) {
                    $this->_addHtmlImagePart($rel, $this->html_images[$i]);
                }
                for ($i=0; $i<count($this->attachments); $i++) {
                    $this->_addAttachmentPart($message, $this->attachments[$i]);
                }
                break;

        }

        if (isset($message)) {
            $output = $message->encode();
            $this->output   = $output['body'];
            $this->headers  = array_merge($this->headers, $output['headers']);

            // Add message ID header
            srand((double)microtime()*10000000);
            $message_id = sprintf('<%s.%s@%s>', base_convert(time(), 10, 36), base_convert(rand(), 10, 36), !empty($GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST']) ? $GLOBALS['HTTP_SERVER_VARS']['HTTP_HOST'] : $GLOBALS['HTTP_SERVER_VARS']['SERVER_NAME']);
            $this->headers['Message-ID'] = $message_id;

            $this->is_built = true;
            return true;
        } else {
            return false;
        }
    }

    /**
    * Function to encode a header if necessary
    * according to RFC2047
    */
    function _encodeHeader($input, $charset = 'ISO-8859-1')
    {
        preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
        foreach ($matches[1] as $value) {
            $replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=" . strtoupper(dechex(ord("\1")))', $value);
            $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
        }
        
        return $input;
    }

    /**
    * Sends the mail.
    *
    * @param  array  $recipients
    * @param  string $type OPTIONAL
    * @return mixed
    */
    function send($recipients, $type = 'mail')
    {
        if (!defined('CRLF')) {
            $this->setCrlf($type == 'mail' ? "\n" : "\r\n");
        }

        if (!$this->is_built) {
            $this->buildMessage();
        }

        switch ($type) {
            case 'mail':
                $subject = '';
                if (!empty($this->headers['Subject'])) {
                    $subject = $this->_encodeHeader($this->headers['Subject'], $this->build_params['head_charset']);
                    unset($this->headers['Subject']);
                }

                // Get flat representation of headers
                foreach ($this->headers as $name => $value) {
                    $headers[] = $name . ': ' . $this->_encodeHeader($value, $this->build_params['head_charset']);
                }

                $to = $this->_encodeHeader(implode(', ', $recipients), $this->build_params['head_charset']);

                if (!empty($this->return_path)) {
                    $result = mail($to, $subject, $this->output, implode(CRLF, $headers), '-f' . $this->return_path);
                } else {
                    $result = mail($to, $subject, $this->output, implode(CRLF, $headers));
                }
                
                // Reset the subject in case mail is resent
                if ($subject !== '') {
                    $this->headers['Subject'] = $subject;
                }
                
                // Return
                return $result;
                break;

            case 'smtp':
                require_once(dirname(__FILE__) . '/smtp.php');
                require_once(dirname(__FILE__) . '/RFC822.php');
                $smtp = &smtp::connect($this->smtp_params);
                
                // Parse recipients argument for internet addresses
                foreach ($recipients as $recipient) {
                    $addresses = Mail_RFC822::parseAddressList($recipient, $this->smtp_params['helo'], null, false);
                    foreach ($addresses as $address) {
                        $smtp_recipients[] = sprintf('%s@%s', $address->mailbox, $address->host);
                    }
                }
                unset($addresses); // These are reused
                unset($address);   // These are reused

                // Get flat representation of headers, parsing
                // Cc and Bcc as we go
                foreach ($this->headers as $name => $value) {
                    if ($name == 'Cc' OR $name == 'Bcc') {
                        $addresses = Mail_RFC822::parseAddressList($value, $this->smtp_params['helo'], null, false);
                        foreach ($addresses as $address) {
                            $smtp_recipients[] = sprintf('%s@%s', $address->mailbox, $address->host);
                        }
                    }
                    if ($name == 'Bcc') {
                        continue;
                    }
                    $headers[] = $name . ': ' . $this->_encodeHeader($value, $this->build_params['head_charset']);
                }
                // Add To header based on $recipients argument
                $headers[] = 'To: ' . $this->_encodeHeader(implode(', ', $recipients), $this->build_params['head_charset']);
                
                // Add headers to send_params
                $send_params['headers']    = $headers;
                $send_params['recipients'] = array_values(array_unique($smtp_recipients));
                $send_params['body']       = $this->output;

                // Setup return path
                if (isset($this->return_path)) {
                    $send_params['from'] = $this->return_path;
                } elseif (!empty($this->headers['From'])) {
                    $from = Mail_RFC822::parseAddressList($this->headers['From']);
                    $send_params['from'] = sprintf('%s@%s', $from[0]->mailbox, $from[0]->host);
                } else {
                    $send_params['from'] = 'postmaster@' . $this->smtp_params['helo'];
                }

                // Send it
                if (!$smtp->send($send_params)) {
                    $this->errors = $smtp->errors;
                    return false;
                }
                return true;
                break;
        }
    }

    /**
    * Use this method to return the email
    * in message/rfc822 format. Useful for
    * adding an email to another email as
    * an attachment. there's a commented
    * out example in example.php.
    */
    function getRFC822($recipients)
    {
        // Make up the date header as according to RFC822
        $this->setHeader('Date', date('D, d M y H:i:s O'));

        if (!defined('CRLF')) {
            $this->setCrlf($type == 'mail' ? "\n" : "\r\n");
        }

        if (!$this->is_built) {
            $this->buildMessage();
        }

        // Return path ?
        if (isset($this->return_path)) {
            $headers[] = 'Return-Path: ' . $this->return_path;
        }

        // Get flat representation of headers
        foreach ($this->headers as $name => $value) {
            $headers[] = $name . ': ' . $value;
        }
        $headers[] = 'To: ' . implode(', ', $recipients);

        return implode(CRLF, $headers) . CRLF . CRLF . $this->output;
    }
} // End of class.
?>
 
if you must use those scripts then i'd suggest going to the author of the scripts (whoever manages your templating system) to request the changes.

although we could suggest just adding a file input control to your form and adding some processing to the receiving script this might well break the templating system and thus be counterproductive.
 
Hi jpadie - thanks for your time.
Unfortunately support seems to be a bit lacking from the template designers.
What about the other option of starting from the ground up?

Thanks.
 
here is a proof of concept script that should be easily adaptable for you.

Code:
<?
function displayForm(){
?>
<style type="text/css">
body, input {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;}
input {margin-top: 3px;}
label {font-weight:bold;}
.message {width:25%; border:dotted red 1px; background-color:#FFE1E1; padding: 5px; margin-left:2px; }
.mainForm {width:25%;}
</style>
<? if (!empty($GLOBALS['message'])): ?>
<div class="message">
<?=$GLOBALS['message']?>
</div>
<? endif; ?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data">
<fieldset class="mainForm" >
<legend>Upload file test script</legend>
<label>Type your name</label><br/>
<input type="text" name="posterName" /><br/>
<label>Select file for upload (max 3MB)</label><br/>
<input type="hidden" name="MAX_FILE_SIZE" value="3145728"/>
<input type="file" name="uploadedFile" /><br/>
<input type="submit" name="submit" value="Upload" style="float:right; margin-right: 10px;" />
</fieldset>
</form>
<?

}
//test to see whether the form was submitted
		
if (isset($_POST['submit'])):
	//set up some useful variables
	//mail parameters
	$to = 		"			";
	$from = 	"			";
	$subject = 	"Test message";
	$t = 		date("j M Y, H:i:s");
	
	
	$errArray = array(
		"UPLOAD_ERR_OK",
		"The uploaded file exceeds the value permitted in php.ini",
		"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
		"The uploaded file was only partially uploaded",
		"No file was uploaded",
		"",
		"Missing a temporary folder",
		"Failed to write file to disk"
		);
	
	$permittedFileTypes = array(
		"pdf",
		"doc",
		"txt");
	
	//pick up the form variables and clean them a bit
	$name = !empty($_POST['posterName']) ? trim($_POST['posterName']) : "No name provided";
	
	//test to make sure that the file upload was ok,
	//if not provide the user with a sensible message
	if ($_FILES['uploadedFile']['error'] !== 0):
		$GLOBALS['message'] = "File did not upload ok.  Error was: ". $errArray[$_FILES['uploadedFile']['error']];
		displayForm();
		exit;
	endif;
	
	//find out the extension of the uploaded file.
	//this is not a foolproof method !!!!
	$pathinfo = pathinfo($_FILES['uploadedFile']['name']);
	$extension = $pathinfo['extension'];
	if (!in_array($extension, $permittedFileTypes)):
		$GLOBALS['message'] = "Forbidden file type uploaded";
		displayForm();
	endif;
	
	//we're pretty much ok at this point so it's time to send the mail
	//create the message
	
	$msg = <<<STR
A contact form was uploaded at $t.

The user gave his name as $name.

The user uploaded a file called {$_FILES['uploadedFile']['name']}.

The uploaded file was {$_FILES['uploadedFile']['size']} bytes.
STR;
	
	//encode the uploaded file for email sending
	//use base 64
	$fileContents = file_get_contents($_FILES['uploadedFile']['tmp_name']);	
	
	//create a boundary for multipart messages
	$b = md5(time());
	$sep = "\n";
	//create the headers for a multipart email
	
	$headers  = "From: $from$sep";
	$headers .= "To: $to$sep";
	$headers .= "Return-Path: $from$sep";
	$headers .= "MIME-Version: 1.0$sep";
	$headers .= "Content-Type: multipart/mixed; boundary=\"$b\"$sep";
	$headers .= "$sep";	

	//add useful information for bad email clients
	
	$message = "This is a multi-part message in mime format $sep";
	$message .= "$sep";	

	//create the message part
	$message .= "--$b$sep";
	$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"$sep";
	$message .= "Content-Transfer-Encoding: 8bit$sep";
	$message .= "$sep";
	$message .= $msg;
	$message .= "$sep";
	$message .= "$sep";
	
	//create the attachment part
	$message .= "--$b$sep";
	$message .= "Content-Type: application/octet-stream$sep";
	$message .= "Content-Transfer-Encoding: base64$sep";
	$message .= "Content-Disposition: attachment; filename=\"{$_FILES['uploadedFile']['name']}\" $sep";
	$message .= "$sep";	
	$message .= chunk_split( base64_encode($fileContents), 76, $sep );
	$message .= "$sep";
	//finish the mail
	
	$message .= "--$b--$sep";

	//send the mail
	$result = @mail($to, $subject,$message, $headers);
	if ($result):
		$GLOBALS['message'] = "Mail was sent.  Try again?";
	else:
		$GLOBALS['message'] = "Mail was not sent.  Try debugging!";
	endif;
	displayForm();
else:	
	displayForm();	
endif;
?>
 
Sorry if I've wasted your time but I've now got this far with modding what I have:

I've created this using the htmlMimeMail functions above:

Code:
$lAttach='c:\test.doc';
require_once('htmlMimeMail.php');
$mail = new htmlMimeMail();
$attachment = $mail->getFile($lAttach);
$mail->setText($lEmailBody);
$mail->addAttachment($attachment, 'Attachment.doc', 'application/vnd.ms-word');
$mail->setFrom($lContactName);
$result = $mail->send(array('$lRecieveName <$lRecieveEmail>'));

But it's producing this:

Warning: fopen(c:\test.doc): failed to open stream: No such file or directory in /home/content/t/b/c/tbc1/html/htmlMimeMail.php on line 173
/var/chroot/home/content/t/b/c/tbc1/dead.letter... Saved message in /var/chroot/home/content/t/b/c/tbc1/dead.letter

This seems to refer to this:

Code:
 function getFile($filename)
    {
        $return = '';
        if ($fp = fopen($filename, 'rb')) {
            while (!feof($fp)) {
                $return .= fread($fp, 1024);
            }
            fclose($fp);
            return $return;

        } else {
            return false;
        }
    }
 
Kind of looks like you need to add "/var/chroot" to your filename.

Code:
if ($fp = fopen("/var/chroot".$filename, 'rb')) {
 
If your server mentions paths like:

[tt]/home/content/t/b/c/tbc1/html/htmlMimeMail.php[/tt]

then

[tt]c:\[/tt]

won't ever exist on the server (where your code is running). Also, you can't use a reference like "c:\anything.txt" to reference a file on the client because there is no permanent connection between the client and the server and when there is a connection, it is not a connection of the type for general file networking to work.

The user will have to first upload the file to the server then refer to the uploaded file. See for a good discussion of handling file uploads with PHP.



Want the best answers? Ask the best questions! TANSTAAFL!
 
Adding "/var/chroot" just changes the message to:
Warning: fopen(/var/chrootc:\test.doc) etc.

OK, looks like I need a PHP Developer as I'm WAY out of my depth here.

Thanks guys.
 
go back to basics.

look at my code and make sure you understand it. it's commented and with the php manual you should be able to get a grip on it. if you have questions, post back. at worst it will help you fix the code that you're working on.

you should also have a look on the net for some basic tutorials on linux. you are developing on a linux machine and not a windows machine. linux does not name its drives and directories in the same way as windows.
 
Thanks jpadie.
I can code VB, etc. on Windows so you're right, I just need to persevere with something that's a bit different.
:->
 
Dumb question, is your form field type "FILE"?

It looks like it might be TEXT, which is why you're getting the filename, not the contents of the file.

You also want to test this with a small file, because a field of type FILE actually uploads the file.
 
@Miros: that looks very promising as a diagnosis. this could happen even if the control type was file but the code referenced the POST value of the element (for some browsers only).

@MrTBC: remember that the actual filename of the uploaded file on your server is stored in the array element $_FILES['name_of_file_control']['tmp_name'].
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top