Lesson 23 - Magic Quotes

Features

"Sets the magic_quotes state for GPC (Get/Post/Cookie) operations.
When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically."

To learn more about magic quotes.

The intent behind magic quotes was good, but it has turned out to be painful. However, your ISP may have enabled them (as mine has) and you no choice but to live them.

 

Request Info Pretty
Click here to see a larger image

Actions

Arrow Red Right Click to see Lesson23_MagicQuotes.php in action on this tutorial site. Note: if you enter name an email in this form, you will send me an email.

Download this file: Lesson23_MagicQuotes.txt to your PC. Change the txt extension to php. Change the “recipient address” in the Lesson23 file and the pointers to the style sheet and then upload all to your website. The “thank yous” should be there from the previous lesson.

Surf to the Lesson23_MagicQuotes.php file on your website with your browser. You should see results similar to the image above on the right.

After completing the form and clicking “Send me more info”, you should receive an email with this in the body:

Please send me more information about Acme products
First Name = your first name
Last Name = your last name
Email = you@yourdomain.com

My interests are:
Favorite Characters = Bugs Bunny, Daffy Duck, Wiley Coyote
Age Group = Adult
Add me to mailing list = No

Comments =first line
second line
third line

And, you should receive a confirming email.

And, you should be sent to the Thank You page.

Gotchas

None.

Source Code

This is all standard HTML stuff, except that we have to retain all the typed-in values when we print error messages.

  <?php
  ob_start
();  /* Start buffer so we can use header anywhere in the page  */
  
/*  magic_quotes is ON and this causes a problem whenever the visitor types a single double quote in the input area for a variable
    as the act of posting (i.e., whenever the visitor clicks on submit) performs the equivalent of add_slashes.
    Single quotes (') get escaped with a backslash (\) and we need to remove them.
    Double quotes (") get escaped with a backslash AND a word inside a pair ("example") gets evaluated to nothing, causing the word example to disappear.
    So, we replace the " with &quot; so that it displays correctly and is NOT evaluated.  */
foreach ($_POST as $tempRowNumber => $temp)

    
$_POST[$tempRowNumber] = str_replace("\\"""$_POST[$tempRowNumber]);
    
$_POST[$tempRowNumber] = str_replace("\"""&quot;"$_POST[$tempRowNumber]);
}  
?>
  
<html>
<head>
  <title>A Request Info Form with more form objects.</title>
  <link rel="stylesheet" href="/PHP_Tutorials/Styles/PHP_Tutorials_Forms_Style.css" type="text/css">
</head>

<body>
<h1>Request Information from the Acme Company</h1>
<form method="POST" name="FirstEmailForm" action="<?php echo($PHP_SELF); ?>" >
  <table width="550" border="0" cellspacing="2" cellpadding="0" bgcolor="#DFDFDF">
    <tr>
      <td colspan="2" class="FormCategoryName">About You</td>
    </tr>
    <tr>
      <td width="200" class="FormVariableName" align="right">
        First Name:<span style="color:red">*</span>
      </td>
      <td width="344">
        <input type="text" name="contactFirstName" value="<?php print $_POST['contactFirstName']; ?>" >
        &nbsp;<span class="Footer" style="color:red">* = Required</span>
      </td>
    </tr>
    <tr>
      <td width="200" class="FormVariableName" align="right">
        Last Name:<span style="color:red">*</span>
      </td>
      <td width="344">
        <input type="text" name="contactLastName" value="<?php print $_POST['contactLastName']; ?>" >
      </td>
    </tr>
    <tr>
      <td width="200" class="FormVariableName" align="right">
        Email:<span style="color:red">*</span>
      </td>
      <td width="344">
        <input type="text" name="contactEmail" value="<?php echo $_POST['contactEmail']; ?>" >
      </td>
    </tr>
    <tr>
      <td valign="Top" class="FormCategoryName" colspan="2">Interests</td>
    </tr>
            
      <td align="right" valign="Top" class="FormVariableName">Favorite Characters:</td>
            <td valign="Top">
<?php
if($_POST['contactCharacterBugs'] == "YES")
$cbvalue "checked"; }
else
$cbvalue "unchecked"; }
echo(
"<input type='checkbox' name='contactCharacterBugs' value='YES'" .$cbvalue .">Bugs Bunny<br>");
if(
$_POST['contactDaffy'] == "YES")
$cbvalue "checked"; }
else
$cbvalue "unchecked"; }
echo(
"<input type='checkbox' name='contactDaffy' value='YES'" .$cbvalue .">Daffy Duck<br>");
if(
$_POST['contactRoadRunner'] == "YES")
$cbvalue "checked"; }
else
$cbvalue "unchecked"; }
echo(
"<input type='checkbox' name='contactRoadRunner' value='YES'" .$cbvalue .">Road Runner<br>");
if(
$_POST['contactCoyote'] == "YES")
$cbvalue "checked"; }
else
$cbvalue "unchecked"; }
echo(
"<input type='checkbox' name='contactCoyote' value='YES'" .$cbvalue .">Wiley Coyote");
?>
              </td>
          </tr>
    <tr>
      <td  align="right" valign="Top" class="FormVariableName" width="200"> Age Group:</td>
      <td valign="Top" width="344">
        <select name="contactAgeGroup">
          <option value="NONE">Select One</option>
          <option value="Kid">Child</option>
          <option value="Teen">Teenager</option>
          <option value="TatooFreak">GenX</option>
          <option value="Adult">Adult</option>
          <option value="OldFart">Senior</option>
<?php  
switch ($_POST['contactAgeGroup'])
{
  case 
"Kid":
    print (
"<option value=\"Kid\" selected>Child<option>");
    break;
  case 
"Teen":
    print (
"<option value=\"Teen\" selected>Teenager<option>");
    break;
  case 
"TatooFreak":
    print (
"<option value=\"TatooFreak\" selected>GenX<option>");
    break;
  case 
"Adult":
    print (
"<option value=\"Adult\" selected>Adult<option>");
    break;
  case 
"OldFart":
    print (
"<option value=\"OldFart\" selected>Senior<option>");
    break;
}
?>
        </select>
     </td>
    </tr>
    
          
    <tr>
            
      <td  align="right" valign="Top" class="FormVariableName" width="200">Please add to me to your mailing list:</td>
      <td valign="Top" width="344">
        <?php
if ($_POST['contactAddMailingList'] == "YES")
{
echo (
"<input type='radio' name='contactAddMailingList' value='YES'  checked>YES<br>
       <input type='radio' name='contactAddMailingList' value='No'>No"
);
}
elseif (
$_POST['contactAddMailingList'] == "No")
{
echo (
"<input type='radio' name='contactAddMailingList' value='YES'>YES<br>
       <input type='radio' name='contactAddMailingList' value='No' checked>No"
);
}
else
{
echo (
"<input type='radio' name='contactAddMailingList' value='YES'>YES<br>
       <input type='radio' name='contactAddMailingList' value='No'>No"
);
}
?>
          
       </td>
    </tr>
    <tr>
      <td  align="right" valign="Top" class="FormVariableName" width="200">Comments:</td>
      <td valign="Top" width="344">
        <textarea name="contactComments" rows="4" cols="40"><?php print $_POST['contactComments']; ?></textarea>
      </td>
    </tr>
    <tr>
      <td width="200" class="FormVariableName" align="right">
      </td>
      <td width="344">
        <input type="hidden" name="firstPass" value="No">
        <input type="submit" name="subRequestButton" value="Send me more info">
        <br>
        <span class="Footer">Please click only once.</span>
      </td>
    </tr>
  </table>
</form>

<?php

if($_POST['firstPass'] == "No")
{

  
/*  Because earlier we replaced all typed-in " with &quot;, we now have to reverse that action so that email is correct */
  
foreach ($_POST as $tempRowNumber => $temp)
  { 
    
$_POST[$tempRowNumber] = str_replace("&quot;""\""$_POST[$tempRowNumber]);
  }

  
/* Set variables equal to their "posted" values". We need to do this because "register_globals = off" is the default.  */
  
$contactFirstName $_POST['contactFirstName'];
  
$contactLastName $_POST['contactLastName'];
  
$contactCharacterBugs $_POST['contactCharacterBugs'];
  
$contactDaffy $_POST['contactDaffy'];
  
$contactRoadRunner $_POST['contactRoadRunner'];
  
$contactCoyote $_POST['contactCoyote']; 
  
$contactEmail $_POST['contactEmail'];
  
$contactAgeGroup $_POST['contactAgeGroup'];
  
$contactAddMailingList $_POST['contactAddMailingList'];
  
$contactComments $_POST['contactComments'];

  
/* If the user skipped required fields or entered invalid values, write an appropriate error message. */
  
if ($contactFirstName == "")
    exit(
"<p class='PhpError'>Your First Name is missing.</p>");
  if (
$contactLastName == "")
  {
    exit(
"<p class='PhpError'>Your Last Name is missing.</p>");
  }
  if (!(
eregi("^[a-z0-9\._-]+@+[a-z0-9\._-]+\.+[a-z]{2,4}$",$contactEmail))):
    exit(
"<p class='PhpError'>Email Address appears to be invalid.</p>");
  endif;
  
$emailDomain ltrim(strstr($contactEmail'@'), '@');   
  if(!(
checkdnsrr($emailDomainANY)))
    exit(
"<p class='PhpError'>Email Address Domain can not be found on the internet.</p>");
    
  
/* Construct list of favorite characters  */
  
$favoriteCharactersList "";
  if (
$contactCharacterBugs == "YES")
     
$favoriteCharactersList .= "Bugs Bunny, ";
  if(
$contactDaffy == "YES")
     
$favoriteCharactersList .= "Daffy Duck, ";
  if(
$contactRoadRunner == "YES")
     
$favoriteCharactersList .= "Road Runner, ";
  if(
$contactCoyote == "YES")
     
$favoriteCharactersList .= "Wiley Coyote";
    
  
/* Construct the email messages  */
  
$messageToAcme "Please send me more information about Acme products";
  
$messageToAcme .= "\n\n First Name = " $contactFirstName;
  
$messageToAcme .= "\n Last Name = " $contactLastName;
  
$messageToAcme .= "\n Email = " $contactEmail;
  
$messageToAcme .= "\n\n My interests are:";
  
$messageToAcme .= "\n Favorite Characters = " $favoriteCharactersList;
  
$messageToAcme .= "\n Age Group = " $contactAgeGroup;
  
$messageToAcme .= "\n Add me to mailing list = " $contactAddMailingList;
  
$messageToAcme .= "\n\n Comments = " $contactComments;
  
$fullAcmeName $contactFirstName ." " .$contactLastName;
  
$mailAcmeHeaders "From: \"".$fullAcmeName."\"<".$contactEmail.">\n";  
  
$mailAcmeHeaders .= "Reply-to: ".$contactEmail;
  
  
$messageToRequestor "Thanks, " .$contactFirstName .", for requesting information about Acme products";
  
$messageToRequestor .= "\n Your email will totally ignored just like 38% of the F500 ignore emails.";
  
$mailRequestorHeaders "From: \"Dave Barnes\"<dave@marketingtactics.com>\n";  
  
$mailRequestorHeaders .= "Reply-to: " ."dave@marketingtactics.com";
  
  
  
/* You need to change dave@marketingtactics.com to YOUR email address  */
  
if (mail("dave@marketingtactics.com""Please Send Acme Info"$messageToAcme$mailAcmeHeaders))
  {
    
mail ($contactEmail"Acme Request Received"$messageToRequestor$mailRequestorHeaders);
    
header("Location: ../../ThankYous/Thanks_Request_Info_Success.html");  /* Redirect browser */
    
exit;                                                  /*   Make sure that code below does not get executed when we redirect. */
  
}
  else
  {
    
header("Location: ../../ThankYous/Thanks_Request_Info_Failure.html");
    
mail("webmaster@marketingtactics.com""Acme, Request Info Failure"$messageToAcme$mailAcmeHeaders);
    exit;
  }
}
?>


</body>
</html>
<?php
  ob_end_flush
();
?>

Final Thoughts

The future lessons will not worry about magic quotes. Whether they are enabled or not is not critical and handling them clutters up our code.

Go To MarketingTactics home