0

php second if validation is not working

second if that is : $firstnameErr = "Only letters and white space allowed "; is not working directly it redirect to success.php.

help me friends

<?php
    $firstname="";
    $firstnameErr="";
    
    if ($_SERVER['REQUEST_METHOD']== "POST") {
       $valid = true;
         
     if(empty($_POST["fname"]))
    {
        $firstnameErr="*firstname is Required";
        $valid=false;   
    }
    else
    {
    $firstname=test_input($POST["fname"]);
     if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
           {
           $firstnameErr = "Only letters and white space allowed"; 
           }    
    } 
       
     //if valid then redirect
      if($valid){
          include 'database.php';
          echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';    
        exit;
    //   header('Location: datasubmitted.php');
    //   exit();
      }  
    
    }
    
    function test_input($data)
    {
         $data = trim($data);
         $data = stripslashes($data);
         $data = htmlspecialchars($data);
         return $data;
    }
    
    ?>
Community
  • 1
  • 1
Geetha
  • 353
  • 3
  • 7
  • 14

1 Answers1

0

When firstname has extra characters other than letters & white spaces you need to set $valid to false. Otherwise it would redirect to success irrespective of what characters it contains.

       $firstname=test_input($_POST["fname"]); //<-- changed this line. you have missed "_"
       if (!preg_match("/^[a-zA-Z ]*$/",$firstname))
       {
          $firstnameErr = "Only letters and white space allowed"; 
          $valid = false; //<-- Add this line
       }   
hemanth
  • 1,033
  • 8
  • 12