Home arrow MySQL arrow Page 2 - Protect Your Users Email With PHP and MySQL
MYSQL

Protect Your Users Email With PHP and MySQL


Eric reports how you, as a webmaster, must know how to protect your readers and members email adresses with the email.php file.

Author Info:
By: Eric 'phpfreak' Rosebrock
Rating: 5 stars5 stars5 stars5 stars5 stars / 10
March 14, 2003
TABLE OF CONTENTS:
  1. · Protect Your Users Email With PHP and MySQL
  2. · Creating Your Custom Mail Function and the 'email.php' Script
  3. · Email.php Code Breakdown
  4. · Conclusion

print this article
SEARCH DEVARTICLES

Protect Your Users Email With PHP and MySQL - Creating Your Custom Mail Function and the 'email.php' Script
(Page 2 of 4 )

Creating Your Custom Mail Function

When we start thinking about using the mail() function, there's a few parameters we have to pass to it. These include who you're going to send mail to, who the mail is from, the subject, message and the headers. Some of these may require you to look them up each time you need to use the mail function, so we'll just create our own mail function and we'll know exactly what to pass to this function each time we need it.

This file is named "email.inc" and it will be included when you need to use your custom mail function. It would look something like this:

function send_mail($to_name, $to_email, $from_name, $from_email, $subject, $message){
    // strip the slashes out of these strings.
    while(list($key,$val)=each($_REQUEST)){
        $$key = stripslashes( $val );
    }

    mail("$to_name<$to_email>", $subject, $message, "From: $from_name<$from_email>nX-Mailer: PHP/" . phpversion());
}

This file starts out by creating a function called send_mail and we have some parameters included that the function will use. These parameters are as follows:

$to_name - This is the person's name that you are sending the mail to.
$to_email - The person's email address you are sending mail to.
$from_name - The person's name who is actually sending the mail.
$from_email - The person's email who is sending the mail.
$subject - The subject line of the email.
$message - The email body.

After we initialize this new function, we're going to do something that makes life a little easier with register_globals turned off. We basically take each item that is sent to this script and use the $_REQUEST superglobal because it pretty much picks up everything including $_POST and $_GET responses. This code below turns those $_POST['varname'] strings into $varname and it even stripslashes those escape characters out of your strings for you which is much simpler to work with. Take a look below:

while(list($key,$val)=each($_REQUEST)){
    $$key = stripslashes( $val );
}

I'm going to go ahead and explain this really quick because I use it multiple times in this tutorial. Basically what's happening here is we take each $_REQUEST item in the scope and use what we call variable variables. This creates a variable with the key name and then stripslashes the value. The end result as I said a moment ago is a $variable. This is much easier to use than typing $_POST['variable']; each time you need to use it.

Let's move on to the PHP mail function that we're customizing.

mail("$to_name<$to_email>", $subject, $message, "From: $from_name<$from_email>nX-Mailer: PHP/" . phpversion());

This is as simple as it gets. My example is pretty much straight out of the PHP Manual and is pretty basic. We start out by passing the variables I mentioned above to this function and then we add the correct headers with the mail function. This set of headers works just fine in almost every case: "nX-Mailer: PHP/" . phpversion()" This header contains the leading n line break (carriage return) which will prevent that BareLF issue found on alot of QMail servers.

Note: You will find in the example files a section of this email.inc that allows you to log each email sent with your MySQL database.

Well, we have now made a file that includes the mail function. All we have to do now is include it wherever we want to send mail, then call the function and pass the variables to it. No more memorizing header information or the correct syntax of the PHP Mail function.

Let's move on to the arms and legs of this whole operation since we've already mastered the heart surgery.

The 'email.php' Script

Now that we have our email.inc file done, we'll start working on a script called "email.php". This script does all the hard work, hiding the user's email address and even validating the form. We'll start out by passing some information to the script to ensure that we actually get the correct user to send the emails to.

In the example file found at the end of this tutorial, I've included a script called "index.php" This script simply creates a list of the first 5 users in your website and gives you a hyperlink to send them an email, which in turn takes them to the email form. We do this by creating the hyperlink like:

email.php?userid=XXXXX where XXXX is the userid from the database (a numerical number that is the primary Key, auto_increment).

This script also utilizes a switch system which allows us to combine multiple operations that would normally be in a single php script. Consider it basically a navigational system. Hopefully you'll be able to figure out how to use it after this tutorial. If not, you may want to consider going to this tutorial: Function Based PHP

Let's take a look at this script now. Don't be affraid, I'll cover it in the end.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Make Email Contact</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<?php
// Make database connection.
include 'db.php';
// Simple conversion for register_globals OFF
while(list($key,$val)=each($_POST)){
    $$key = stripslashes( $val );
}
function email_form($from_name, $from_email, $subject, $message){
    while(list($key,$val)=each($_POST)){
    $$key = stripslashes( $val );
    }
    // Look up the person's first name that they are trying to contact
    $sql = mysql_query("SELECT * FROM users WHERE userid = '".$_REQUEST['userid']."'") or die (mysql_error());
    while($row = mysql_fetch_array($sql)){
        foreach( $row AS $key => $val ){
            $$key = stripslashes( $val );
        }
        // Remove the space after first name if no last name
        // is in the database
        if(!$last_name){
            $username = $first_name;
        } else {
            $username = "$first_name $last_name";
        }
        // Include the email_form.html
        include 'email_form.html';
    }
    // Free the mysql result.
    mysql_free_result($sql);
}
// Begin Script Navigation
switch($_REQUEST['cmd']){
    // The default case to show for this switch. If none is specified
    // this case will be used. In other words, the "index" of this script.
    default:
    // call the email_form function above.
    email_form($from_name, $from_email, $subject, $message);
    // end this case.
    break;
   // Form Validation. If you called this script by:
    // email.php?cmd=validate_form  you would be here:
    case "validate_form":  
    if(!$from_name || !$from_email || !$subject || !$message){
        echo "<h4>There were errors with your submission! Please Complete the form and try again!</h4>";
        email_form($from_name, $from_email, $subject, $message);
    } else {
        // If all is good, send the email!
        $sql = mysql_query("SELECT * FROM users WHERE userid = '$userid' ") or die (mysql_error());
        while($row = mysql_fetch_array($sql)){
            foreach( $row AS $key => $val ){
                $$key = stripslashes( $val );
            }   
            // simple name check. Remove the space after the first name
            // if there is no last name in the database.
            if(!$last_name){
                $to_name = $first_name;
            } else {
                $to_name = "$first_name $last_name";
            }
            // Note: We got the users's email address from the database.
            // Since we used a quick method of generating strings, we now
            // have $email_address with the email address of the person we are
            // trying to contact.  We can now pass this to the send_mail function
            // in place of $to_email.
            
            // Now, include the email.inc and send the email by calling the funciton
            // with the applicable strings attached.
            
            include 'email.inc';
            send_mail($to_name, $email_address, $from_name, $from_email, $subject, $message);
            echo "<h1>Your Mail has been sent!</h1>";
            
        } // end $sql array  
    } // end if else check for valid form post.   
    break;
}
?>
</BODY>
</HTML>


blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials