contact form upload file in magento


As i know this is not a good way, but really a fast hack if you want to attach a file with contact us form.

1. Edit your form.phtml under ‘/app/design/frontend/[your-interface]/[your-theme]/template/contacts/form.phtm ‘ and add ‘enctype=”multipart/form-data”‘

1
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">

add file upload field

1
<input name="attachment" id="attachment" class="input-text" type="file" />

Now edit your contacts controller ‘\app\code\core\Mage\Contacts\controllers\IndexController.php’
first find near line 91-93

1
2
3
if ($error) {
       throw new Exception();
}

Add this after this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$fileName = '';
               if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
                   try {
                       $fileName       = $_FILES['attachment']['name'];
                       $fileExt        = strtolower(substr(strrchr($fileName, ".") ,1));
                       $fileNamewoe    = rtrim($fileName, $fileExt);
                       $fileName       = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
                       $uploader       = new Varien_File_Uploader('attachment');
                       $uploader->setAllowedExtensions(array('zip', 'jpg','pdf', 'rar', 'png', 'eps', 'ai'));
                       $uploader->setAllowRenameFiles(false);
                       $uploader->setFilesDispersion(false);
                       $path = Mage::getBaseDir('media') . DS . 'contacts';
                       if(!is_dir($path)){
                           mkdir($path, 0777, true);
                       }
                       $uploader->save($path . DS, $fileName );
                   } catch (Exception $e) {
                       $error = true;
                   }
               }

And after

1
$mailTemplate = Mage::getModel('core/email_template');

Add this

1
2
3
4
5
6
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
               if(file_exists($attachmentFilePath)){
                   $fileContents = file_get_contents($attachmentFilePath);
                   $attachment   = $mailTemplate->getMail()->createAttachment($fileContents);
                   $attachment->filename = $fileName;
               }

That’s it, enjoy email attachement

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s