Home arrow MySQL arrow Page 3 - Protect Your Users Email With PHP and 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
  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

Protect Your Users Email With PHP and MySQL - Email.php Code Breakdown
(Page 3 of 4 )

The script you saw on the last page will be broken down into parts and explained so you can get a better understanding of what goes on during this process.

The top portion is just standard HTML. You can replace it with your header.php if you would like.

Let's begin at the PHP.

// Make database connection.
include 'db.php';

This portion starts the PHP engine and then includes a file called 'db.php'. The db.php establishes a persistent connection with your MySQL database and allows you to you to start executing queries. An example of what this script should include is found here.

The next code chunk was already described earlier, except this one uses the $_POST because we don't want $_REQUEST superglobals being passed into this script.

// Simple conversion for register_globals OFF
      $$key = stripslashes( $val );

Next we'll move on to the first function. I wrote this portion as it's own function because we'll do some form validating against the posted fields and if they aren't validated true, we'll just call this function again until the person gets everything filled out in the form fields.

I'm going to break this function down as we go.

function email_form($from_name, $from_email, $subject, $message){
      $$key = stripslashes( $val );

For some reason, I have found that declaring the variables above to be intermittent. So, I simply declared a new function called "email_form" and told PHP that I'll be passing the four variables into it that are defined between the ( and ). The reason we are going to set this function up to pass variables into it is because we will validate this form later on. So we'll need to pass the information that the user already entered into the forms back to this function so we can fill out the affected form fields again. Next, I used my register_globals fix on this function and we're ready to move on.

// 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 );

The above code chunk will look up the user's first and last name from the database based on the $userid that was passed to this script. There's also a simple way of turning each column name into a $variable format and stripslashes the value.

// Remove the space after first name if no last name
// is in the database
    $username = $first_name;
} else {
    $username = "$first_name $last_name";

I used the above code chunk to eliminate any spaces after the first name if there is no last name in the database. This just makes things look cleaner.

<hr class="horizorange" size="1">
// Include the email_form.html
include 'email_form.html';

If everything is working properly and you have passed a valid userid and results were returned, the above code chunk will include the 'email_form.html' file and present the user with a form to fill out. You will have to take a look at this html file inside the source code file at the end of the tutorial to see how I set it up to fill out the form fields if the validation failed.

// Free the mysql result.

It never hurts to free mysql results. They are always freed at the end of the script, but I like to put this in there anyways, just an old habbit and every little bit helps.

Let's move on to the navigational "switch" system and I'll also show you the validation case which validates the form and decides whether to send the user back to the form or send the email. Once again, I'll break this code into chunks and describe it as we go.

// Begin Script Navigation

Above we have initialized a switch called "cmd" You can name it whatever you want, however you must alter the URLs and Forms that are posting to this script to reflect your changes. It works by a query string similar to this: email.php?cmd=validate_form&item1&item2&item3 etc... You do not have to put the "cmd=" for the default case in this switch, example: email.php?userid=1

// 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.

We have just notified PHP that if no switch or case was defined, we'll use the following as the default:

// call the email_form function above.
email_form($from_name, $from_email, $subject, $message);

// end this case

After each case, you can prevent other cases from being executed by calling a break; which ends the switch.

Let's move on to our next case, the "validate_form" case.

// Form Validation. If you called this script by:
  // email.php?cmd=validate_form you would be here:
  case "validate_form":

Declare your 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 {

The code above should look pretty familiar if you followed my Creating a Membership Tutorial. We're validating this form to ensure that no fields on the form were empty. If they are empty, we'll simply call back the first function in this script called "email_form" and send the variables to it that we already have.

Note: when calling a function such as email_form you MUST have the same amount of values passed to it as the original function had declared. This is incorrect: email_form($from_name); You have 3 less fields on this function call than your original functions. You need 4 total. Got it? Good!

Let's get this email sent if all is good! Do you remember that I told you the email address will NEVER be visible to anyone even if you are viewing the source? Here's how we do that. You will never post the recievers email address in your form posts, that defeats the purpose. So, we'll use the $userid and look the email address up in the MySQL database and retrieve the user's name and email address and pass that information into send_mail function that we created in the email.inc file.
// 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.
            $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.

The rest of the script is fairly easy to figure out. Just follow the comments in the code and you'll be set.

blog comments powered by Disqus

- 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 

Developer Shed Affiliates


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