从一个页面跳转到另一个页面时提交的php验证

时间:2015-10-30 08:10:53

标签: php html

在这个程序中,当我点击提交按钮时,页面直接进入其他页面2222.php。错误消息没有弹出..我只是想在点击提交按钮时点击错误消息...

php_validation.php

<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"]))  //----------------------------------------------       -------------------------
{
$nameError = "Name is required";
} 
else 
{
$name = test_input($_POST["name"]);  
// check name only contains letters and whitespace
 if (!preg_match("/^[a-zA-Z ]*$/",$name)) 
 {
 $nameError = "Only letters and white space allowed";
 }
 //-----------------------------------------------------------------------

 }
if (empty($_POST["email"])) //----------------------------------------------    -------------------------
{
$emailError = "Email is required";
} 
else 
 {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) 
 {
 $emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"])) 
{
$genderError = "Gender is required";
} 
else 
 {
 $gender = test_input($_POST["gender"]);
 }
 }
function test_input($data) 
{     
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
 }
?>

<h2>PHP Form Validation Example</h2>

<p><span class="error">* required field.</span></p>

<form method="post" name="myForm" action="2222.php"> 

 <p>First Name:
  <input type="text" name="fname"  id="fname" />
  <span class="error">* <?php echo $nameError;?></span>
 </p>
 <br><br>
 <p>
 Email: 
 <input type="text" name="email" id="email">
 <span class="error">* <?php echo $emailError;?></span>
 </p>
 <br><br> 
 <p>  
 Gender:
 <input type="radio" name="gender" value="female">Female
 <input type="radio" name="gender" value="male">Male
 <span class="error">*<?php echo $genderError;?></span><br><br />  
 </p>
 <input class="submit" type="submit" name="submit" value="Submit" >

 </form>
 </body>

2222.php

 <?php
 $name =  $_POST['fname'];
 $email =  $_POST['email'];
 $radio =  $_POST['gender'];

 echo "<h2>Your Input:</h2>";
 echo "user name is: ".$name;
 echo "<br>";
 echo "user email is: ".$email;
 echo "<br>";
 echo "user is ".$radio;
 ?>

4 个答案:

答案 0 :(得分:1)

所以我为你做了一个快速的代码:

这是你的“php_validation.php”:

<?php

//Init error var
$nameError = '';
$emailError = '';
$genderError = '';

//Did we have an error ?
if(isset($_GET['error'])){

    //Split error return into an array
    $errorList = explode('_', $_GET['error']);

    //Verify every possible error
    if(in_array('name',$errorList)){
        $nameError = 'Please enter your name<br>';
    }

    if(in_array('email',$errorList)){
        $emailError = 'Please enter your email<br>';
    }

    if(in_array('gender',$errorList)){
        $genderError = 'Please enter your gender';
    }
}


?>

我没有改变表格

然后这是你的“2222.php”:

<?php
$error ='';

function test_input($data) 
    {     
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
 }


//When we receive data
if(isset($_POST)){

    //Verify all possible data and set error
     if(!empty($_POST['fname'])){
        $name =  test_input($_POST['fname']);
     }else{
        $error .= 'name_'; 
     }

     if(!empty($_POST['email'])){
        $email =  test_input($_POST['email']);
     }else{
        $error .= 'email_';
     }
     if(!empty($_POST['gender'])){
        $radio =  test_input($_POST['gender']);
     }else{
        $error .= 'gender_';
     }

     //if we have an error then redirect to form with error
     if(!empty($error)){
        header("Location:php_validation.php?error=".$error);
     }
}
 ?>

也没有在此页面上更改您的输出。

正如我之前所说,当你点击提交按钮时,你会发生什么:

  1. 提交点击
  2. 表单发送到2222.php为$ _POST,您被重定向到此页面
  3. 如果您的表单在其他页面上发布而不是在进行检查的页面上发布,则无法正常工作。

答案 1 :(得分:0)

由于您的表单操作是&#34; 2222.php&#34;,点击提交按钮会在执行任何操作之前自动将您重定向到2222.php。

如果您想查看表单收到的内容,可以在&#34; 2222.php&#34;中执行,然后将错误消息重定向到php_validation.php

答案 2 :(得分:0)

您可以执行以下操作之一:

  1. 在Javascript&#34; onClick&#34;中进行所有检查。功能

  2. 执行Ajax调用&#34; onClick&#34;到处理程序页面,从该页面获取验证消息。

  3. 在&#34; 2222.php&#34;上进行验证。页

  4. 回到同一页面的行动(因为你在这里做了一些验证)并在&#34; 2222.php&#34;上验证后重定向页

  5. 现在只取决于适合您程序的人。

答案 3 :(得分:0)

如果您希望保持在同一页面上,则可以将表单提交给iframe,因为处理脚本的结果将显示在iframe中。

示例:

个文件:

  • 文件与 - form.php的
  • 形式提交处理-file.php

代码示例:

文件与 - form.php的

<!DOCTYPE html>
<html>
<head>
    <title>[Your page title]</title>
</head>
<body>
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field.</span></p>

    <!-- Form -->
    <form action="[path-to-form-submit-process]" method="[GET|POST]" 
          target="form-processor">
        <div>
            <label>First Name:
                <input type="text" name="fname"  id="fname" />
                <span class="error">* <?php echo $nameError ?></span>
            </label>
        </div>
        <div>
            <label>Email:
                <input type="text" name="email" id="email">
                <span class="error">* <?php echo $emailError ?></span>
            </label>
        </div>
        <div>
            <label>Gender:
                <p><input type="radio" name="gender" value="female"> Female</p>
                <p><input type="radio" name="gender" value="male"> Male</p>
                <p><span class="error">*<?php echo $genderError ?></span></p>
            </label>
        <input class="submit" type="submit" name="submit" value="Submit" >
        </div>
    </form>

    <!-- The iframe to submit the form to -->
    <iframe name="form-processor" id="form-processor" 
            src="[path-to-form-submit-process]"></iframe>

    <!-- 
    NOTE: The error message spans are left there just because you had them 
    in your code, those will not work here at this point, actually depending 
    on your php configuration will most probably throw errors/warnings, 
    because such variables were not defined at all...
    -->
</body>
</html>

如:

  • [path-to-form-submit-process] - 要替换​​为文件/控制器的URL的占位符 - &gt;处理传递的表单数据的操作
  • [*] - 应使用您的案例值替换的占位符

形式提交处理-file.php

<?php 

# Processing the form fields and displaying the messages
$post = $_POST;

# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable

# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];

function addErrorMessage($message, &$messages, &$errorFlag)
{
    $errorFlag = true;
    $errorMessageTemplate = '<p class="error-message">{message}</p>';
    array_push($messages, str_replace('{message}', $message, 
        $errorMessageTemplate));
}

// Validating the email
$email = array_key_exists('email', $post) 
    ? $post['email']
    : null;

if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    // Raising the flag for an error on validation
    addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}

// ........
// validation of rest of fields
// ........

$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
    // ........
} catch (Exception $e) {
    $internalError = true;
}

# Stop execution on internal error
if ($internalError === true) 
{ 
    ?>
    <h2>Sorry, there's an error on our side... we'll do all in our 
        powers to fix it right away!</h2>
    <?php
    exit;
}

# Displaying the results
if ($invalidFormData === true) {
    // Building errors message
    $messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
    $messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}

// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);

// Displaying the messages:
echo implode('', $messages);

但是我相信这应该通过一个AJAX调用来完成。 在这种情况下还有很多不好的做法,所以我建议将一些设计模式和架构作为MVC进行检查,并考虑使用像Symfony / Laravel / CodeIgniter这样的框架...有很多工具可以制作你的生活更轻松:)