Member Sign In
Not a member?

A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.


It's fast and free.

Sign in with OpenID
Sign In
Webmonkey is a property of Wired Digital.
processing...
Join Webmonkey

Please send me occasional e-mail updates about new features and special offers from Wired/Webmonkey.
Yes No

Please send occasional e-mail offers from Wired/Webmonkey affiliated web sites and publications, and carefully selected companies.
Yes No

I understand and agree that registration on or use of this site constitutes agreement to Webmonkey's User Agreement and Privacy Policy.
Webmonkey is a property of Wired Digital.
processing...

Retrieve Sign In

Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.

or
Webmonkey is a property of Wired Digital.
processing...

Welcome to Webmonkey

A private profile page has been created for you.
As a member of Webmonkey, you can now:
  • edit articles
  • add to the code library
  • design and write a tutorial
  • comment on any Webmonkey article
Close
Webmonkey is a property of Wired Digital.

Sign In Information Sent

An e-mail has been sent to the e-mail address registered in this account.
If you cannot find it in your in-box, please check your bulk or junk folders.
Sign In
Webmonkey is a property of Wired Digital.

Sending e-mail with FLASH and PHP

/skill level/
/viewed/
0 Times

Current revision (00:33, 10 December 2008) (edit) (undo)
m
 
(2 intermediate revisions not shown.)
Line 1: Line 1:
-
 
+
== Intro ==
-
== Introduction ==
+
So, you have decided to build a website using Adobe Flash because you want to show off your designing skills. Excellent! You also want the visitors to your website to send you a message now and then, maybe to ask you questions about your content, a product you are offering, or simply to say "Hello! Is it me you're looking for?" ''Blast you, Lionel Ritchie!'' That's good! Any web builder worth his/her weight in salt knows that it is a good idea to have a "Contact Us" page.
So, you have decided to build a website using Adobe Flash because you want to show off your designing skills. Excellent! You also want the visitors to your website to send you a message now and then, maybe to ask you questions about your content, a product you are offering, or simply to say "Hello! Is it me you're looking for?" ''Blast you, Lionel Ritchie!'' That's good! Any web builder worth his/her weight in salt knows that it is a good idea to have a "Contact Us" page.
"Uhm, dude? I, like, totally don't know how to send e-mails with Flash." No worries, ''dude''! I will show you how to create a Contact Us form using Flash and make it functional with PHP. It's not as hard as you might think...
"Uhm, dude? I, like, totally don't know how to send e-mails with Flash." No worries, ''dude''! I will show you how to create a Contact Us form using Flash and make it functional with PHP. It's not as hard as you might think...
 +
 +
'''NOTE:''' The tutorial below uses ActionScript 2.0. If you are using Adobe Flash CS3 or higher, make sure your publish settings are set for AS 2.0, as the code will not work in AS 3.0. A tutorial using AS 3.0 may be in the works.
== What you'll need ==
== What you'll need ==
-
# Adobe Flash and basic Actionscript knowledge. See the [[Tutorial:Flash_Tutorial_for_Beginners|Flash Tutorial]] if you need to.
+
# Adobe Flash and basic Actionscript 2.0 knowledge. See the [[Tutorial:Flash_Tutorial_for_Beginners|Flash Tutorial]] if you need to.
# A server with PHP installed (preferably the latest version)
# A server with PHP installed (preferably the latest version)
# A server with ''sendmail'' or equivalent installed
# A server with ''sendmail'' or equivalent installed
Line 162: Line 163:
Earlier, I told you to access the query string directly by putting a $ in front of the variable passed by Flash. I also warned you that your PHP installation must be explicitly set for this. Newer versions of PHP have set the dafault to $_POST['var_name'] or $_GET['var_name'], depending on which method you used to pass the query. If you want to directly access the query as I described in this tutorial, you will need to change the php.ini configuration to allow for this. If you don't have access to the php.ini file, then just use the $_POST or $_GET globals; 'tis no big deal.
Earlier, I told you to access the query string directly by putting a $ in front of the variable passed by Flash. I also warned you that your PHP installation must be explicitly set for this. Newer versions of PHP have set the dafault to $_POST['var_name'] or $_GET['var_name'], depending on which method you used to pass the query. If you want to directly access the query as I described in this tutorial, you will need to change the php.ini configuration to allow for this. If you don't have access to the php.ini file, then just use the $_POST or $_GET globals; 'tis no big deal.
-
The PHP validation code is rather extensive, so I will not include it here. However, being the cool monkey that I am, I will link you to a ZIP file which contains the FLA and PHP files.
+
The PHP validation code is rather extensive, so I will not include it here. However, there are many many sites that talk about it. Google it up.
-
[http://www.loshernandez.net/source/Flash_tutorial.zip Flash_tutorial.zip]
+
Thank you for reading this tutorial, and have a wonderful day!

Current revision

Contents

Intro

So, you have decided to build a website using Adobe Flash because you want to show off your designing skills. Excellent! You also want the visitors to your website to send you a message now and then, maybe to ask you questions about your content, a product you are offering, or simply to say "Hello! Is it me you're looking for?" Blast you, Lionel Ritchie! That's good! Any web builder worth his/her weight in salt knows that it is a good idea to have a "Contact Us" page. "Uhm, dude? I, like, totally don't know how to send e-mails with Flash." No worries, dude! I will show you how to create a Contact Us form using Flash and make it functional with PHP. It's not as hard as you might think...

NOTE: The tutorial below uses ActionScript 2.0. If you are using Adobe Flash CS3 or higher, make sure your publish settings are set for AS 2.0, as the code will not work in AS 3.0. A tutorial using AS 3.0 may be in the works.

What you'll need

  1. Adobe Flash and basic Actionscript 2.0 knowledge. See the Flash Tutorial if you need to.
  2. A server with PHP installed (preferably the latest version)
  3. A server with sendmail or equivalent installed
  4. A basic understanding of Flash element definitions (i.e. text fields, instance names, etc.), as well as familiarity with PHP programming.

Most servers (especially Linux installations) come with PHP and sendmail out of the box. If your site is hosted by someone else, chances are they have already taken care of these details; but you may want to check with them.

Steps

Setting up the form

Alright! Let's get our paws dirty, shall we? The first thing we need to do is build the form on our stage in Flash. Every good "Contact Us" form has these elements:

  • The sender's e-mail address
  • The subject
  • The message
  • A Send button

Optionally, you could add fields for the sender's name and the recipient's e-mail address. Since the scope of this tutorial is to send all messages to a designated recipient, we will scratch the recipient field. But this monkey thinks it's kinda cool to see the sender's name next to the e-mail address, so we will include that field in our form. Ok, so our basic form will look like this on the stage:

All the yellow stuff was created using the Text Tool and setting it to Static Text in the property inspector. The white boxes were also created with the Text Tool; however, the fields were set to Input Text (we want the user to be able to enter stuff in there, right?), and turning on the "Show border around text" option. The message box needs some additional settings:

  1. Set to Multiline
  2. Set the size to whatever fits your design needs

The button was created using the button symbol method. Cool, our form is ready! Now we need to make it functional.

Making the form work

Before we can make the form work, we need to add instance names to our button and input fields. The convention I like to use is to start the name of the instance with the type of object it is. For example, my input fields would have names like tb_from. This way, when I look at the code months from now, I know if am referring to the from text box. So, give your input elements whatever instance names you want. Mine are called tb_name, tb_from, tb_subject, tb_msg, and bt_send. On the timeline, add a layer and call it Actions. Click on a frame and expand the Actions-Frame inspector.

Obviously, when the user clicks on the Send button, we want something to happen, right? Add this code to ActionScript:

1. bt_send.onPress = function () {
2.      var msg_lv = new LoadVars();
3.      var rtn_lv = new LoadVars();
4.      var rtn_lv.onLoad = function(success:Boolean) {
5.          if (success) {
6.             tb_msg.text = rtn_lv.msg_rtn
7.          } else {
8.             tb_msg.text = "Problem connecting to the server.";
9.          }
10.      }
11.      msg_lv.__name = tb_name.text;
12.      msg_lv.__from = tb_from.text;
13.      msg_lv.__subject = tb_subject.text;
14.      msg_lv.__msg = tb_msg.text;
15.      msg_lv.sendAndLoad("/path/to/php/script",rtn_lv,"POST");
16.
17. };
18.
19. stop();

If you are going to copy and paste this code, be sure to remove the numbers at the beginning of each line. I have added them here only for reference.

1. This tells Flash to execute the code between the {} when the user presses on (hence "onPress") the Send button. You would substitute bt_send with the instance name you gave to your button.

2-3. In order for Flash and PHP to communicate, they need to be able to send and receive variables to each other. These variables are contained within a LoadVars object. So, we need to set 2 LoadVars objects, one to send the variables from Flash to PHP (msg_lv), the other to receive the variables sent from PHP to Flash (rtn_lv).

4. rtn_lv will contain the variables sent from PHP to Flash. When these variables are loaded (hence "onLoad"), Actionscript will execute the code inside the {}. The Boolean parameter success is automatically passed by the onLoad function. It will either be TRUE or FALSE, and will be an indication whether Flash and PHP were able to successfully communicate.

5-10. In this if block, we are checking for the result of the onLoad function. So, if (success) is the same as saying if (success == TRUE); since us monkeys like to be efficient, let's make the code short and sweet. In this block, if rtn_lv successfully received variables from PHP, we tell Flash to change the content of the message field (tb_msg) to whatever the value is for the returned variable from PHP (in this case msg_rtn). If the load failed (more than likely because of server connectivity issues), we change the content to "Problem connecting to server."

11-14. Using the msg_lv LoadVars object, we set the variables that will be sent to PHP. I have added double underscores to the names of these variables; again, you can do whatever you want... This doesn't have to be "Monkey see, monkey do!" For example, msg_lv.__name = tb_name.text will set the variable __name to the content inside the tb_name field.

15. This is the reason we are here, folks! The Flash function sendAndLoad is probably one of the most brilliant things Adobe (formerly Macromedia) could have done. As the name implies, this function sends variables to an external processor, waits for a response, and loads this response to another object. Here are the parameters:

  • sendAndLoad(path:String,target:Object,Method:String)
    • path - The URL to the PHP script that will be used.
    • target - The LoadVars object that will be receiving the PHP response (in our case, rtn_lv).
    • Method - This will either be "GET" or "POST." These mean the same in Actionscript as they do in HTML forms. "GET" will pass the variables in the URL string; "POST" will send them in the request headers. I like using the "POST" method. So, on this line of code, we are telling flash to send all the msg_lv variables to the assigned PHP script using "POST," and load the response from PHP into our rtn_lv object.

19. I like to add a stop(); command here; even if your Flash page will only contain one frame, it's a good idea to add it to prevent the player from "reloading" the one and only frame. I have had it happen to me before. It's very annoying...


With me so far? I got a small headache when I was first learning all this. If you need a break, now's the time. Next we will be looking at the PHP code; so, go get drink and/or a snack.

Getting Nasty with PHP

Wow! You actually came back! Awesome! Ready to tackle the PHP side of all this? Cool! Here is the basic code:

1. <?
2.    $r = "\r\n";
3.    $to = "The Awesome Monkey <monkey_mail@mydomain.com>";
4.    $header = "From: ".$__name."<".$__from.">".$r;
5.    $header .= "MIME-Version 1.0".$r;
6.    $header .= "Content-type: text/html; charset=us-ascii".$r;
7.    $header .= "X-Mailer: PHP/".phpversion();
8.    $header .= $r.$r;
9.    $msg = mail($to, $__subject, $header);
10.   if ($msg) {
11.        echo "&msg_rtn=OK!&";
12.   } else {
13.        echo "&msg_rtn=D'oh!&";
14.   }
15. ?>

Remember, if you are going to copy and paste the above code, you will need to remove the line numbers. I have added them only for reference purposes.

I will give you a quick refresher on PHP variables:

  1. They must start with a $ (dollar sign)
  2. You can put two variables together with the "." (period) operator
  3. The ".=" operator is the same as saying $variable = $variable."New Value"
  4. When variables are passed to PHP via a form (whether it is GET or POST), you can access these variables directly by adding a "$" to the field name. In our example, we are passing variables with two underscores (__name, __from, etc.). So, to call on these, we would type $__name and so on. WARNING: Your php.ini file must be setup to allow for this direct access to passed variables in the query string. See the Alternate methods section for different options.

Here is how the code breaks down:

1. Let the server know where your PHP code begins.

2. Set a variable to the line break string. E-mail headers are kind of funny that way. They need line breaks to determine each aspect of the header (from, mime version, etc.).

3. Remember earlier when I explained why we were going to ommit the recipient's e-mail address field from the form? This is why. We are hard coding it. By writing the address the way we did, the e-mail clients will display the name of the recipient rather than the e-mail address.

4. We set the "From" address much like the "To" address, with the person's name before the e-mail address. This way, the e-mail client will display the sender's name rather than the address. It's much like caller ID on your cell phone: it's nicer to see the name than the number, makes it easier to decide whether to ignore the call or not. Add the line break variable.

5. We add the MIME version in which the e-mail is being sent and another line break.

6. We tell the e-mail client what kind of content the message has and how to display it. This can be text/plain or text/html. We also need to tell the client what character set we are using. Don't forget the line break!

7. The "X-Mailer" header is optional. If you pass this on, the client will know that the message was sent using PHP and which version (that's what the phpversion() call does, it returns the version installed on the server).

8. Add 2 line breaks to the header. Trust me! This will save you many headaches. Some e-mail clients don't know when the message body starts unless there are two line breaks preceding it.

9. This is where PHP gets really cool. The mail() function returns a boolean value depending on whether it was able to send the message or not. So, we set the result of the function to a variable I have called $msg. The mail() function takes three parameters: to, subject, and headers. The headers parameter is optional and can be omitted. However, without it, you will not know who sent you the message and you will not be able to reply to it.

10-14. Here is where we talk back to Flash. The if statement checks to see if $msg holds a value of TRUE and prints out one string. If not, it prints out a different string. I'll talk about the return string it a second.

15. Let the server know you are done with the PHP code.

Okay, great! What did I just do? I told PHP to print out (using the echo command) the string &msg_rtn=OK!& or &msg_rtn=D'oh!&, depending on whether $msg was TRUE or FALSE. Notice the & at the beginning and end of the strings. These are here because Flash needs to know where the returned set of variables from PHP starts and ends. This string must be URL encoded, meaning, it has to look like a URL query string (i.e. everything after the ? in a GET request). Flash will then convert the name/value pairs into usable variables. Remember line 6 of the Actionscript code: tb_msg.text = rtn_lv.msg_rtn;? Flash will get the variable msg_rtn (which is on the left of the "=" in the echo string, which will have the value to the right of the "=") and set the text of the message field to whatever PHP sent back; in other words, it will display 3 possible statements:

  1. The message was successfully sent (if onLoad was successful and mail worked)
  2. The message was not sent (if onLoad was successful and mail did not work)
  3. Flash could not connect to the server (if onLoad was not successful)

TA DA!

I know, I know... It looks like a lot of code, and I did say it was not that hard. But think about it: How does e-mail actually work? Would you rather have to code the entire HELO SMTP satements? Would you rather send your visitors to a lame static HTML form when you have worked so hard at designing that AWESOME Flash-based website? Besides, I've already done much of the work for you. The design elements are up to you, but the code to make it work is freely available to you.

But wait! There is more!

Alternate methods

Did you know you could add e-mail validation to your PHP code? Yeah! Really! You can make it so that PHP doesn't even try to send the message if the sender's e-mail address is not in the right format or if it doesn't exist all together. You could even make it so that Flash doesn't call the sendAndLoad function unless the required fields of your choosing are filled out.

Field Validation in Actionscript

In Actionscript, add the following lines of code to your onPress function:

if (tb_name.text eq "") {
    tb_msg.text = "I need a name!";
} else if (another.text eq "") {
    tb_msg.text = "This other field is empty";
} else {
    //Do the sendAndLoad stuff
}

Do an else if for every field you want checked for content, then set the tb_msg field to whatever you want.

Also, in the example, I am telling you to use the same field for your error messages that your visitors use to type out their message to you. You could add another text field, give it the instance name tb_err, set it to Dynamic Text and have the error messages displayed there instead.

PHP Validation

Earlier, I told you to access the query string directly by putting a $ in front of the variable passed by Flash. I also warned you that your PHP installation must be explicitly set for this. Newer versions of PHP have set the dafault to $_POST['var_name'] or $_GET['var_name'], depending on which method you used to pass the query. If you want to directly access the query as I described in this tutorial, you will need to change the php.ini configuration to allow for this. If you don't have access to the php.ini file, then just use the $_POST or $_GET globals; 'tis no big deal.

The PHP validation code is rather extensive, so I will not include it here. However, there are many many sites that talk about it. Google it up.

Thank you for reading this tutorial, and have a wonderful day!

  • This page was last modified 00:33, 10 December 2008.
Edit this article
Reddit Digg
 

/related_articles/

See more related articles

Subscribe now

Special Offer For Webmonkey Users

WIRED magazine:
The first word on how technology is changing our world.

Subscribe for just $10 a year