SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Filter_Var and redirecting page

    I have added the filter_var function in order to validate a user email address entered in a form, but I just get the message "valid email" or "invalid email" after pressing the submit form button, but I want the "invalid email" message to appear on a seperate, even a blank page, instead of, as now, appearing on the result of online test page, which gives the impression that it makes no difference whether the email is valid or not.
    here is the relevant piece of php code:

    Code:
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    
    
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        
    );
    
    $semailSubject = "Someone scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)))
    
    
    
    if (!filter_has_var(INPUT_POST, 'submit')) {
        echo "form";
        // include the form.
    }
     
    $defs = array(
        'senderName'       => array('filter'=>FILTER_SANITIZE_STRING,
                        'flags' => FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW),
        'senderEmail'      => FILTER_VALIDATE_EMAIL,
        'homepage'   => FILTER_VALIDATE_URL,
        'age'        => array(  'filter' => FILTER_VALIDATE_INT,
                                'options'=> array('min_range'=>7, 'min_range'=>77)),
        'income'     => FILTER_VALIDATE_FLOAT,
        'favourites' => array(
                            'filter' => FILTER_SANITIZE_STRING,
                            'flags'  => FILTER_REQUIRE_ARRAY
                        ),
              );
     
    $input = filter_input_array(INPUT_POST, $defs);
     
    if ($input['age'] === FALSE) {
        exit("You must be between 7 and 77 years old.");
    }
     
    if (is_null($input['favourites'])) {
        exit("You have to choose two or more languages.");
    }
     
    if (!in_array('PHP', $input['favourites'])) {
        exit("You don't like PHP!");
    }
     
    /*Other checks for required values */
    
    
    /**
         *
         * @strip injection chars from email headers
         *
         * @param string $string
         *
         * return string
         *
         */
        function safeEmail($string)
        {
            return  preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $string );
        }
    
    
    ?>
    Thanks in advance for any help.

  2. #2
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not a php master, but on this line:
    PHP Code:
    if(mail('myname@hotmail.com'$semailSubjectimplode("\r\n"$aEmailMessage))) 
    This "if" statement needs braces around the 'true' code to work, otherwise it only applies to the next line. Also, it looks like you're sending the mail before you doing your form checking... don't you want to check the form first, if the fields are right, email is right, then send the email, else, write an error?

  3. #3
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    oh? Could you rewrite that piece of code to clarify what you mean?
    Thanks

  4. #4
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Lucky for you I've never used filter_input_array, so I played around with it

    PHP Code:
    <?php

    $ages
    ['min'] = 7;
    $ages['max'] = 77;

    //Form is submitted, run code
    if(filter_has_var(INPUT_POST'go')) {
         
         
    //define filter array
         
    $defs = array(
              
    'senderName'   =>   array(
                   
    'filter'       =>   FILTER_SANITIZE_STRING,
                   
    'flags'        =>   FILTER_FLAG_ENCODE_HIGH|FILTER_FLAG_ENCODE_LOW
              
    ),
              
    'senderEmail'  =>   FILTER_VALIDATE_EMAIL,
              
    'homepage'     =>   FILTER_VALIDATE_URL,
              
    'age'          =>   array(
                   
    'filter'  =>   FILTER_VALIDATE_INT,
                   
    'options' =>   array(
                        
    'min_range'=>$ages['min'],
                        
    'max_range'=>$ages['max']
                   )
              ),
              
    'income'       =>   FILTER_VALIDATE_FLOAT,
              
    'favourites'   =>   array(
                   
    'filter'       =>   FILTER_SANITIZE_STRING,
                   
    'flags'        =>   FILTER_REQUIRE_ARRAY
              
    ),
         );

         
    //filter vars
         
    $filtered_input filter_input_array(INPUT_POST$defs);

         
    //uncomment to look at our form data
         
    echo "<pre>";
         
    var_dump($filtered_input);
         echo 
    "</pre>";

         
    //error array
         
    $form_errors = array();
         
         
    //error checking, could do this with an array and loop too
         
    if ($filtered_input['age'] === FALSE) {
             
    $form_errors[] = "You must be between {$ages['min']} and {$ages['max']} years old.";
         }
          
         if (
    count($filtered_input['favourites']) < 2) {
             
    $form_errors[] = "You have to choose two or more Languages.";
         }
         if (!
    in_array('PHP'$filtered_input['favourites'])) {
             
    $form_errors[] = "How can you not like PHP?";
         }
         
    //do other validations here

         //if there are errors, show them, if not send email...
         
    if(count($form_errors) > 0) {
              
    //show errors
              
    echo "The following errors occurred:<ul>";
              foreach (
    $form_errors as $e) {
                   echo 
    "<li>$e</li>";
              }
              echo 
    "</ul>";
         } else {
              
    //do your mail stuff here
              //mail('email@domain.com', "Subject Here", "Your message Here");
         
    }

    }

    ?>

    <form action="" method="post">
         <p><label for="senderName">Name:</label> <input type="text" name="senderName" id="senderName" value="John Zoidberg"/></p>
         <p><label for="senderEmail">Email:</label> <input type="text" name="senderEmail" id="senderEmail" value="drz@planetexpresscom"/></p>
         <p><label for="homepage">Homepage:</label> <input type="text" name="homepage" id="homepage" value="http://planetexpress.com"/></p>
         <p><label for="age">Age:</label> <input type="text" name="age" id="age" value="300"/></p>
         <p><label for="income">Income:</label> $<input type="text" name="income" id="income" value="500"/></p>
         <p><label>Favourites:</label> <input type="checkbox" name="favourites[]" id="favourites1" value="C++" checked="checked"/><label for="favourites1">C++</label>
              <input type="checkbox" name="favourites[]" id="favourites2" value="ASP"/> <label for="favourites2">ASP</label>
              <input type="checkbox" name="favourites[]" id="favourites3" value="PHP" /> <label for="favourites3">PHP</label>
         </p>
         <p><button type="submit" name="go" value="true">Go</button></p>
    </form>
    You dig?

  5. #5
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    oh.... a bit complicated...I just tried to copy any paste that new code and before pressing "submit" I typed in a false email address for testing, but got no error.

  6. #6
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, because there is no error handling for your email address. You need to add an error message for each field:
    PHP Code:
         if ($filtered_input['senderEmail'] === FALSE) {
             
    $form_errors[] = "Your email is invalid";
         } 
    The filter_input_array just returns a new array, and if the array variable doesn't meet the qualifications, it returns a false value... something has to check if the variable is false... you could loop through all of them, check for a false value, then lookup the error code for that variable in an $error_message array.

  7. #7
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    actually, I have tried another piece of spam stopping code from w3 school, but I still have the problem that after pressing submit, the user is passed to the results page, even if they enter an invalid email address. this is a link to my test page:
    www.profesornativo.com/testing.htm and this is the new code I'm using
    Code:
    // Mail things
    
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    
    
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        
    );
    
    $semailSubject = "Someone scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)));
    
    
    
    function spamcheck($field)
      {
      //filter_var() sanitizes the e-mail 
      //address using FILTER_SANITIZE_EMAIL
      $field=filter_var($field, FILTER_SANITIZE_EMAIL);
      
      //filter_var() validates the e-mail
      //address using FILTER_VALIDATE_EMAIL
      if(filter_var($field, FILTER_VALIDATE_EMAIL))
        {
        return TRUE;
        }
      else
        {
        return FALSE;
        }
      }
    
    if (isset($_REQUEST['senderEmail']))
      {//if "email" is filled out, proceed
    
      //check if the email address is invalid
      $mailcheck = spamcheck($_REQUEST['senderEmail']);
      if ($mailcheck==FALSE)
        {
        echo "Invalid input";
        }
      else
        {//send email
        $email = $_REQUEST['senderEmail'] ; 
        $subject = $_REQUEST['subject'] ;
        $message = $_REQUEST['message'] ;
        mail("someone@example.com", "Subject: $subject",
        $message, "From: $email" );
        echo "Thank you for using our mail form";
        }
      }
    
    
    ?>
    Thank you

  8. #8
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Is this code a part of your results page? Is there any other code, php, html or otherwise in this? You script works as it is, but the result page (or Header redirect) should only be in the "//send email" portion of the script. If the html for that page is after the script, it shows up anyway.
    PHP Code:
    <?php
    if (isset($_REQUEST['senderEmail'])) { //if "email" is filled out, proceed

        //check if the email address is invalid
        
    $mailcheck spamcheck($_REQUEST['senderEmail']);
        if (
    $mailcheck==FALSE) {
            
    ?>
            
    <h1>Invalid Email, Sucker!</h1>
    <p>This is your bad results page HTML!</p>

            <?php
        
    }
        else {
    //send email
            
    $email $_REQUEST['senderEmail'] ;
            
    $subject $_REQUEST['subject'] ;
            
    $message $_REQUEST['message'] ;
            
    mail("someone@example.com""Subject: $subject",
                
    $message"From: $email);
            
    ?>
            
    <h1>Thank you for using our mail form!</h1>
    <p>This is your good results page HTML!</p>

            <?php
        
    }
    }
    ?>

  9. #9
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have a seperate page for the html with:

    Code:
    <form action="result.php" method="post" id="form_id">
    <p>My name &nbsp;<select name="question1">
    <option value="0"></option>
    
    <option value="A">is</option>
    <option value="B">are</option>
    <option value="C">it is</option>
    
    <option value="D">it</option>
    </select>
    <br/><br/>
    
              Name  <input type="text" name="senderName" />
               Email <input type="text" name="senderEmail" />
               
                <input type="submit" name="submit" value="submit" />
    
    <input type=reset value=Clear>
    </form>
    etc
    still trying to figure out how to add that error code so that only a blank page appears with the "invalid email" message

  10. #10
    SitePoint Zealot
    Join Date
    Dec 2006
    Posts
    182
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The code above will do that. There should only be 2 files we're working with... the form page you linked to, and the result.php. The form page posts the data to the result.php, which, if it has a bad email will say so, and if it is good, will send the email and thank the user.

  11. #11
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I finally got it to work, but I don't know wheteher you can give it the thumbs up as being good php?
    I added this piece of code:
    Code:
    if ($mailcheck==FALSE)
     {
    
    
     echo "Invalid email address"; 
      echo "<a href='javascript:history.back(1);'><br/>Return to test </a>";
    die("");
    }
    and the more complete code:
    Code:
    // Mail things
    
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    
    
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        
    );
    
    $semailSubject = "Someone scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)));
    
    
    
    function spamcheck($field)
      {
      //filter_var() sanitizes the e-mail 
      //address using FILTER_SANITIZE_EMAIL
      $field=filter_var($field, FILTER_SANITIZE_EMAIL);
      
      //filter_var() validates the e-mail
      //address using FILTER_VALIDATE_EMAIL
      if(filter_var($field, FILTER_VALIDATE_EMAIL))
        {
        return TRUE;
        }
      else
        {
        return FALSE;
        }
      }
    
    if (isset($_REQUEST['senderEmail']))
      {//if "email" is filled out, proceed
    
      //check if the email address is invalid
    
    
      $mailcheck = spamcheck($_REQUEST['senderEmail']);
      if ($mailcheck==FALSE)
     {
    
    
     echo "Invalid email address"; 
      echo "<a href='javascript:history.back(1);'><br/>Return to test </a>";
    die("");
    }
    
      else
        {//send email
        $email = $_REQUEST['senderEmail'] ; 
        $subject = $_REQUEST['subject'] ;
        $message = $_REQUEST['message'] ;
        mail("someone@example.com", "Subject: $subject",
        $message, "From: $email" );
        echo "";
        }
      }
    
    
    ?>
    Is there any other code I could add to make it more secure, prevent spam etc?
    Thanks.
    Last edited by dubman; Apr 8, 2009 at 17:16.

  12. #12
    SitePoint Addict
    Join Date
    Apr 2003
    Location
    spain
    Posts
    283
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    would this line of code be sufficient to make the name field secure?
    Code:
    $sSenderName = filter_input(INPUT_POST, 'senderName' , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES);
    More complete code:
    Code:
    // Mail things
    
    $sSenderName = $_POST['senderName'];
    $sSenderEmail = $_POST['senderEmail'];
    
    
    
    $aEmailMessage = array(
        'Name: ' . $sSenderName,
        'Email: ' . $sSenderEmail,
        
    );
    
    $semailSubject = "$sSenderName  $sSenderEmail scored ". $score . " over ". $scoremax . "."; ;
    
    if(mail('myname@hotmail.com', $semailSubject, implode("\r\n", $aEmailMessage)));
    
    
    $sSenderName = filter_input(INPUT_POST, 'senderName' , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES);
    
    function spamcheck($field)
      {
      //filter_var() sanitizes the e-mail 
      //address using FILTER_SANITIZE_EMAIL
      $field=filter_var($field, FILTER_SANITIZE_EMAIL);
      
      //filter_var() validates the e-mail
      //address using FILTER_VALIDATE_EMAIL
      if(filter_var($field, FILTER_VALIDATE_EMAIL))
        {
        return TRUE;
        }
      else
        {
        return FALSE;
        }
      }
    
    if (isset($_REQUEST['senderEmail']))
      {//if "email" is filled out, proceed
    
      //check if the email address is invalid
    
    
      $mailcheck = spamcheck($_REQUEST['senderEmail']);
      if ($mailcheck==FALSE)
     {
    
    
     echo "Invalid email address"; 
      echo "<a href='javascript:history.back(1);'><br/>Return to test </a>";
    die("");
    }
    
      else
        {//send email
        $email = $_REQUEST['senderEmail'] ; 
        $subject = $_REQUEST['subject'] ;
        $message = $_REQUEST['message'] ;
        mail("someone@example.com", "Subject: $subject",
        $message, "From: $sSenderEmail" );
        echo "";
        }
      }
     
    ?>
    I uploaded the above code and at least saw no errors reported, so I just want to know if it's ok to sanitize and make the name field secure? Thank you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •