从进程页面到php中的索引页面显示服务器端错误消息

时间:2017-06-02 06:57:57

标签: php html server-side-validation

如果我在一个页面上同时编写代码(HTML和PHP),我必须显示一个服务器端验证错误消息。

现在我有index.php和process.php页面。我必须将server.php中的服务器端验证错误消息传递给index.php。不使用Ajax。你能帮助我吗?

的index.php

<?php

include('../../db/connection.php');
$fname_error="";
$email_error="";
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="process.php" method="post">
        <input type="text" name="fname" value="<?php if(isset($fname)){echo $fname;} ?>">
         <span class="error"><?php echo $fname_error;?></span>

        <input type="email" name="email" value="<?php if(isset($email)){echo $email;}?>">
        <span class="error"><?php echo $email_error;?></span>

        <input type="submit" name="submit">
    </form>

</body>
</html>

Process.php

<?php

include('../../db/connection.php');
if (isset($_POST['submit'])) {

    $fname=trim($_POST['fname']);
    $email=trim($_POST['email']);

    if (empty($fname)) {
        $fname_error="Name is empty";
    }

    else
        {
        if ($fname<3) {
        $fname_error="Please enter minimum 3 character";
    }
}

    if (empty($email)) {
        $email_error="Email field is empty";
    }
    else
        {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $email_error="Invalid email format"; 

    }
    }


    // insert code here
}
?>

1 个答案:

答案 0 :(得分:0)

使用SESSIONS来实现这个目标。请尝试以下代码:

<强>的index.php

<?php
session_start();
include('../../db/connection.php');
$fname_error= $_SESSION['fname'];
$email_error= $_SESSION['email_error'];
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="process.php" method="post">
        <input type="text" name="fname" value="<?php if(isset($fname)){echo $fname;} ?>">
         <span class="error"><?php echo $fname_error;?></span>

        <input type="email" name="email" value="<?php if(isset($email)){echo $email;}?>">
        <span class="error"><?php echo $email_error;?></span>

        <input type="submit" name="submit">
    </form>

</body>
</html>

<?php
    unset($_SESSION['fname']);
    unset($_SESSION['email_error']);
?>

<强> process.php

<?php
session_start();
include('../../db/connection.php');
if (isset($_POST['submit'])) {

    $fname=trim($_POST['fname']);
    $email=trim($_POST['email']);

    if (empty($fname)) {
        $_SESSION['fname'] ="Name is empty";
        header('location:index.php');
    }

    else
        {
        if ($fname<3) {
        $_SESSION['fname'] ="Please enter minimum 3 character";
        header('location:index.php');
    }
}

    if (empty($email)) {
        $_SESSION['email_error'] ="Email field is empty";
        header('location:index.php');
    }
    else
        {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $_SESSION['email_error']="Invalid email format"; 
          header('location:index.php');

    } 
}


    // insert code here
}
?>