Home » ActionScript 3.0, Adobe, Flash AS 3, PHP

Create a contact form with file attachment in FLASH CS, AS 3.0 and PHP

2 September 2009 6 Comments

In this post I’ll show you how to create a form with a file attachment using Flash CS3/4, ActionScript 3.0 and PHP. The trick is use the FileReference class to upload a file from your own hard disk and at the same time send the input- field values.

flashfiledemo

Test a live version filling the following form.
If you write a valid email address and select a file from your hard disk you’ll receive an e-mail in few seconds (speed depend from your server configuration).

This movie requires Flash Player 10

LET’S CREATE THE FORM IN FLASH CS4
The first stuff to do is create the Flash UI.
The following image is self-explanatory but if you’re lazy you can download it from the source code (see at the end of article ; )

flashfile

CREATE THE DOCUMENT CLASS (full-commented)
com.fabiobiondi.core. ContactFormAttachment.as

package com.fabiobiondi.core {
 
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.DataEvent;
 
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.FileReference;
	import flash.net.URLLoader;
 
 
 
	public class ContactFormAttachment extends Sprite { 
 
		private var request:URLRequest ;
		private var fileRef:FileReference;
 
 
		/**
		* Constructor
		*/
		public function ContactFormAttachment() {
 
			// New File Reference istance, adding all the listeners
			fileRef = new FileReference();
			fileRef.addEventListener(Event.SELECT, selectHandler);
			fileRef.addEventListener(Event.COMPLETE, completeHandler);
			fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadComplete);
 
			// Button Click events
			selectFile_btn.addEventListener(MouseEvent.CLICK, openDialog)
			sendAll_btn.addEventListener(MouseEvent.CLICK, sendAll)
		}
 
 
 
 
		/**
		* Open the browser file window
		*/
		private function openDialog(event:MouseEvent):void{
			fileRef.browse();
		}
 
 
 
		/**
		* Dispatched when the user selects a file for upload or download from the file-browsing dialog box.
		*/
		private function selectHandler(event:Event):void{
 
			// Get file info
			var file:FileReference = FileReference(event.target);
 
 
			// check if file < 50kb
			if (file.size < 50000) {
 
				// The PHP Script to call
				request = new URLRequest("ContactFormAttach.php");
				// For Debug purpose
				//request = new URLRequest("http://www.fabiobiondi.com/blog/wp-content/samples/2009_09_01_FlashAS3_FormAttachment/ContactFormAttach.php");
 
 
				// Set variables to send
				request.method = URLRequestMethod.POST;
				request.data = new URLVariables();
				request.data.mail_txt = mail_txt.text;
				request.data.name_txt = name_txt.text;	
				request.data.msg_txt = msg_txt.text;	
 
				// Display File information (name + size)
				pathFile.text = file.name + " (" + file.size + " Kb)"
 
			} else {
				// File >= 50kb
				pathFile.text = "File size must be < 50kb"
 
			}
 
 
 
		}
 
 
 
 
 
		/**
		* Submit the form 
		* Invoked after submit button click event
		*/
		private function sendAll(event:MouseEvent):void{
 
			// If email is not valid we stop the submit
			if (!isEmailValid(mail_txt.text)) {
				mail_txt.text = "Email is not valid";
				return;
			}
 
 
			/*
			* 'request' property will be 'null' if a file is not yet selected and the form shouldn't be sent
			*
			* NOTE: in a real scenario you should allow to send a form without a file selection
			* and you should manage this form in a different way, avoid using FileReference
			*/
			if (request != null) {
 
				// Submit form uploading the selected file
				fileRef.upload(request);
 
 
			} else  {
				// Display a msg if any file is selected
				pathFile.text = "Please select a file from your HD (with size < 50kb)";
			}
 
		}
 
 
 
 
		/**
		* Dispatched periodically during the file upload or download operation 
		* NOTE: it's useful to get the upload progress percentage)
		*/
		private function progressHandler(event:ProgressEvent):void {
			// Display upload file progress
			pathFile.text = int((event.bytesLoaded / event.bytesTotal)* 100) + "%"
		}
 
 
 
 
		/**
		* Dispatched when download is complete or when upload generates an HTTP status code of 200.
		*/
		private function completeHandler(event:Event):void {
			pathFile.text = "Loading Complete"
		}
 
 
 
		/**
		* Dispatched after data is received from the server after a successful upload.
		*/
		private function uploadComplete(e:DataEvent):void {
 
			var mailResponse:Object = e.data
 
			// Email sent with success
			if (mailResponse == "1") {
 
				// Change SUBMIT button status to disable
				sendAll_btn.label = "SENT"
				sendAll_btn.enabled = false;
 
				// Reset form fields
				mail_txt.text = "";
				name_txt.text = "";
				msg_txt.text = "";	
 
				// Set to null the request object
				request = null
 
			} else {
				pathFile.text = "There are some server side issue";
 
			}
 
		}
 
 
		/**
		* CHECK EMAIL VALID
		* Return TRUE = Email valid | FALSE = Email Wrong
		*/
		private function isEmailValid(mail:String):Boolean {
			var emailRegEx:RegExp = /^[a-z][w.-]+@w[w.-]+.[w.-]*[a-z][a-z]$/i;
 
			if (!emailRegEx.test(mail)) {
 
				return false
			} else
				return true;
		}
 
 
 
	}
 
}

THE PHP CODE (full-commented)

I’m not so expert in PHP so to accomplish this article I have searched information around the web and merged code from different websites (see www.php.net to get more samples )
I’m sorry for the php quality code and if I can’t give you too much support about it but I hope to provide you more than an inspiration.

<?php
 
 
header("Cache-Control: no-cache, must-revalidate");
 
//  Mime Creation
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
 
 // ================================================================================================================================
 // Open the upload files to be ready for the attachment
 // ================================================================================================================================
$tmp_name = $_FILES['Filedata']['tmp_name'];
$type = $_FILES['Filedata']['type'];
$name = $_FILES['Filedata']['name'];
$size = $_FILES['Filedata']['size'];
 
// if the upload succeeded, the file will exist
if (file_exists($tmp_name)){
 
	// check to make sure that it is an uploaded file and not a system file
	if(is_uploaded_file($tmp_name))
	{
 
		// open the file for a binary read
		$file = fopen($tmp_name,'rb');
 
		// read the file content into a variable
		$data = fread($file,filesize($tmp_name));
 
		// close the file
		fclose($file);
 
		// now we encode it and split it into acceptable length lines
		$data = chunk_split(base64_encode($data));
	}
 }
 
 
 
// ================================================================================================================================
// now we'll build the message headers
// ================================================================================================================================
$headers = "From:".$_REQUEST[email_txt]."rn" . "MIME-Version: 1.0rn" . "Content-Type: multipart/mixed;rn" . " boundary="{$mime_boundary}"";
 
 
 
// ================================================================================================================================
// Message to send
// ================================================================================================================================
$subject = "ActionScript 3.0 - Form attachmentn";
$message.= "ActionScript 3.0 - Form attachmentn";
$message.= "---------------------------------------------n";
$message.= "SENDER INFORMATION:n";
$message.= "nMail: ".$_REQUEST[mail_txt]."n";
$message.= "nName: ".$_REQUEST[name_txt]."n";
$message.= "---------------------------------------------n";
$message.= "nMessage: ".$_REQUEST[msg_txt]."n";
 
 
$message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/plain; charset="iso-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";
 
$message .= "--{$mime_boundary}n" .
"Content-Type: {$type};n" .
" name="{$name}"n" .
"Content-Transfer-Encoding: base64nn" .
$data . "nn" .
"--{$mime_boundary}--n";
 
 
 
 
// ================================================================================================================================
// Send Email
// ================================================================================================================================
// NOTE: in a real scenario you shouldn't send back the email to the sender,
// but you should set the customer email (i.e. info@company.com instead $_REQUEST[mail_txt])
 
if (@mail($_REQUEST[mail_txt], $subject, ($message), $headers)){
	// Return 1 if everything is ok and mail is sent
	echo "1";
}
else {
	// Return 0 if there are problems while sending mail
	echo "0";
}
 
 
?>

Naturally it’s only a sample and in a real scenario a form should allow people to send a message without an attached file,you should improve the form validation and so on.

Download Source Code (FL CS4)

6 Comments »

  • Alex said:

    Would be difficult to add a button to remove upload and to implement multiupload
    follwoing this same methode?

    Regards!

  • Fabio Biondi (author) said:

    Hi Alex, the server side code should change to accept multiple files and from AS3 side you should use FileReferenceList instead of FileReference.

    Check Google to see some examples (i.e. I found this useful post but i didn’t tried it yet because mail attachment is a bit different from the classic multiple upload).

    I’m sorry but I can’t do it quickly. It’s not so easy to implement and it could requires many tests to check if everything works well when you send emails… . As I wrote in the article (because I imagined to receive questions) I’m not so skilled in php but I will think about it for a future tutorial

  • Alex said:

    Hi

    Thanks for replying.
    I had luck by getting the solution from other programmer.
    The form wasn’t working quite well, once the “exclude” button was not functional. Now it works all better. I still don’t have the solution for the last bug, but I can’t blame: it’S free source from 1. quality (as yours) and the owner has is own things to do.

    THE BUG: if you first upload a file to the server (before clicking on send button) and if you try to reset (LIMPAR) the file isn’t removed neither from DATAGRID nor from server.

    I think you’ll be happy as soon as you get this file. Perhaps it is what you are looking for: Flash email AS2 php anexo.rar

    http://www.4shared.com/file/94408185/5daec304/Flash_email_AS2_php_anexo.html?err=no-sess

    Best regards!

  • emailregex | EMAIL said:

    [...] Fabio Biondi Blog » Blog Archive » Create a contact form with file … [...]

  • adriano said:

    Great. Just great.

  • web tasarimi said:

    thanks for sharing. nice article..

    web_tasarimi

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.