![]() |
|
![]() |
| Using the mail() function |
| For a while, now, I've had my email address available in plain view on my web site for all to see. I really should have thought that idea through before I did it, because humans aren't the only ones who see that email address. I opened the door to every email spider out there on the internet. So far I've been lucky, and I haven't been inundated with ridiculous amounts of spam because of my actions. Tony from XenoCafe recommended that I post a user submission page, where the user posts a comment and the comment is emailed to me. Tony has already implemented this on his site so I thought I'd give it the old college try and make one of my own. |
The mail() function is used to send email with php. It uses sendmail under Unix to send the email, so you need sendmail running in order to use it. You can also use qmail or postfix, but you need to be sure to use the appropriate sendmail wrappers that come with them. Under windows, it makes a connection to an SMTP server. The mail is sent directly to the person in the argument used to specify the recipient of the email. In this case, we are going to use youremail@yourserver.com. Let's get to the code. Too easy. |
|
| Okay, that was simple. Now save that code and name the file user_submit.php. When we create our html form, 'user_submit.php' will be used in the form action element. Now this is where we put the code to good use. We will create a simple html form to get all of the data our php script needs to send comments out as email. I won't bother with writing tables, as this is only conceptual. |
|
| Keep in mind that this form was written under the assumption that register_globals is turned on in php.ini. As of PHP version 4.2.0, register_globals is off by default. The source code at the bottom of the page will show you how to write your php script with register_globals turned off. Anyhow, if you have register_globals enabled, php takes the names of the formfields and turns them into variables. For instance, UserComments in the textarea formfield is actually turned into the variable $UserComments in our php script, which is used as the body of our message. Likewise, the EmailAddress text field is turned into $EmailAddress in the php script, which is used for the "from" field of the email. Coding like this is a horrible habit to get into, as allowing php to create variables like this is a huge security risk.. Read more about the issues with register_globals here . I am a bad, bad man. Source Code: Here is the source code for the PHP email script. I have zipped two versions of the code. One for use with register_globals ON and one for use with register_globals OFF. They are both included in phpmail.zip |