如何在PHP中检查表单提交?

In my form, there are some fields, which I want to check before submitting the form. If there are errors, the form would not be submitted and the user would be alerted with an error.

For that purpose, I am trying to catch the event where the form is submitted, in php. I should get an alert with text "Submitted". However, I don't. What mistake am I doing?

<?php
if(isset($_POST['submit']))
    echo "<span>Submitted!</span>";
    sleep(2);
?>

<form action="next_page.php" method=post> 
*Other fields beside input*
<input type="submit" name="submit" value="Submit form"> <br>
</form>

alert() is not a function provided by PHP, so it will error.

You seem to be confusing it with JavaScript.

To output text from PHP you need to echo it or put it outside of <?php ... >? blocks. To run JavaScript, you need a <script> element.

<?php
if(isset($_POST['submit'])) {
?>
    <script> alert("Submitted!"); </script>
<?php
}
?>

<form action="next_page.php" method=post> 
    <!-- You also need to have a form control that matches the test you are doing -->
    <button name="submit" value="X">Submit</button>
</form>

Your form is missing the submit type. Also you need to echo the alert box, since alert() is NOT a PHP function.

<?php if(isset($_POST['submit']))
    echo"<script>alert('Submitted!');</script>"; ?>

<form action="next_page.php" method=post>  
<input type = "submit" name = "submit" value = "Sub"/> 
</form>

There are plenty of ways to accomplish what you would like to accomplish. Are you using any kind of framework? It might have built in for this. Generally it's not a bad idea to to rely on standard functions or libraries to do verification.

If not you will have to do it yourself and decide whenever you'd like it to be server-side (php) or user-side (javascript). Regardless you should verify it server-side to catch any malicious submits.

If we go with your example it might look like this for server-side php verification which echos its results back to the user. Beware that this is really, really insecure as it's using $_GET which might be modified etc.

<?php
$username = '';
$warning = '';

if(isset($_POST['submit'])){
    if(!empty($_POST['username']) && strlen(trim($_POST['username'])) != 0){
        $username = $_POST['username'];
        if(strlen($username) > 8){
            $warning = 'Only 8 characters allowed!';
        }else{
            header("Location: next_page.php");
        }
    }
    else
    {
        $warning = 'Username is empty, please provide a valid name.';
    }
}
?>
<form action="form.php" method="post"> 
    <input type="text" name="username" value="<?php echo($username); ?>" />
    <?php echo($warning); ?>
    <input type="submit" name="submit" />
</form>

This snippet would preserve input in case anything is wrong and only redirect to the next page if the data was valid. An example using jQuery could look like this:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>event.preventDefault demo</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>


    <form action="form.php" method="post"> 
        <input type="text" name="username" id="formUsername" />
        <span id="warning"> </span>
        <input type="submit" name="submit" />
    </form>

    <script>
    $(document).ready(function() {

        $("form").submit(function( event ) {
            var username = $("#formUsername").val().trim();

            if(username.length > 0 && username.length < 9){
                $("form").submit();
            }
            else if(username.length > 8)
            {
                $("#warning").text("More than 8 characters.");
                event.preventDefault();
            }
            else{
                $("#warning").text("Empty username?");
                event.preventDefault();
            }
        });

    });
    </script>
</body>
</html>

As I understand you are trying to output a message on the same page after the form is submitted, not an alert. The action attribute on the HTML form tag redirects you to the next_page.php. So leave the action attribute blank, and after you've validated all your fields use php header() function to redirect to next_page.php. Be aware not to output any of the message before the header() function, it will fail in this case. Do smthing like this:

<?php
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
    $err_message = '';
    //validate your fields
    if($_POST['yourfield'] == ''){
        $err_message = 'Please check your fields';
    }
    //other validations
    ...
    if($err_message == ''){
       //redirect to your next page
       header('Location:next_page.php');
       //prevent further code execution
       exit();
    }
    //output your message
    echo $err_message;
}
?>

<form action="" method=post> 
*Other fields beside input*
<input type="submit" name="submit" value="Submit form"> <br>
</form>

There's many ways you can do it.

Here again is an alternative if you wanted to keep it based under an echo:

<?php
if (isset($_POST['submit']))
{
    echo '<script>alert("Submitted!");</script>';
}
?>

<form action="" method=post>
    *Other fields beside input*
    <input type="submit" name="submit" value="Submit form"> <br>
</form>

EDIT: Generally I try to leave the PHP in the top of the same page rather than having it point elsewhere as there's not much need to do it.

The way I solved it was using Jquery, with something like as shown below.

$('#form1').submit(
    function() {
        //your validation rules here
        var email = $('#YourEMail').val()
        if(!validEmail(email))
        {
            $('#invalidAlert').html('<i>Invalid e-mail address!</i>')
            return false;
        }
        else 
            return true;
    });