开发者

PHP: IF statement question

开发者 https://www.devze.com 2023-04-02 03:46 出处:网络
I\'ve a basic login form to which I want to add some validations. I came up with these: $errors = array();

I've a basic login form to which I want to add some validations. I came up with these:

$errors = array();

if($_SERVER['REQUEST_METHOD'] == 'POST'){

    if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
        $errors['email'] = "Please enter a valid email address";
    }

    if(0 === preg_match("/.{6,}/", $_POST['password'])){
        $errors['password'] = "Please enter you correct password";
    }

    if(0 === count($开发者_JAVA百科errors)){
      // SUBMIT THE FORM, <form action='auth.php' method='post'...
    }
}

So, how can I accomplish the last IF part, which will submit the form if there's no error? Thanks in advance


I think you're trying to use PHP in a situation where you need JavaScript.

If you're talking about actually submitting a <form> element on an HTML page, then you need JavaScript. PHP only fires, in this case, when the form is submitted.

If, however, your intent isn't to submit the form element and instead perform a task (or series of tasks) based on a validated form, then you would just have to include your logic appropriately.

For example:

if( count($errors) > 0 ){
  // THERE IS A PROBLEM, RETURN THE ERRORS
  include( 'myHTML.html' );
  exit();
}

// If the above didn't fire, then we have no errors
echo( "Wonderful! Now we can add this information to a database, or something." );


I would imagine if this code is in auth.php then you are already submitting the form.

Think of it this way: You submit the form no matter what, but stop the submission if there are errors. You process may look something like the following:

form.php

<?php 
   if($_GET['error']){ echo '<p>There was a problem with your input</p>'; }
?>
<form method="post" action="auth.php">
   <input ... />
   <button type="submit">Submit</button>
</form>

auth.php

 $errors = array();

 if($_SERVER['REQUEST_METHOD'] == 'POST'){

     if(0 === preg_match("/.+@.+\..+/", $_POST['email'])){
         $errors['email'] = "Please enter a valid email address";
     }

     if(0 === preg_match("/.{6,}/", $_POST['password'])){
         $errors['password'] = "Please enter you correct password";
     }
 }

 if(0 === count($errors)){
   // do your form action as normal
 }
 else {
    header('Location: form.php?error=1');
    exit();
 }


I don't see a problem there. The only thing you should do is move the if-part up so it will only be called when the request method is post. Is this solving your problem? If not, please describe your problem in detail.

0

精彩评论

暂无评论...
验证码 换一张
取 消