简体   繁体   English

如何使用PHP和HTML验证表单?

[英]How to validate form with PHP and HTML?

I am currently working on a project for a web development class I am taking in which I have to create a registration page for a marketing product and add user details to a database. 我目前正在从事一个Web开发课程的项目,该课程必须为市场营销产品创建注册页面并将用户详细信息添加到数据库中。 I've got the basic code working but, after speaking with my teacher, I need to add some form of data validation to the website. 我已经使用了基本代码,但是在与老师交谈之后,我需要向网站添加某种形式的数据验证。 I have tried marking the input fields as required in HTML5 as well as using a separate JavaScript Validator but nothing works, if I submit the form, my PHP script process without the data being validated. 我尝试将输入字段标记为HTML5中的必填字段,并尝试使用单独的JavaScript验证程序,但是如果提交表单,我的PHP脚本过程而没有验证数据,则无济于事。

My goal is for the data to validated directly on the form, so that error messages appear on the form itself versus on a separate page. 我的目标是直接在表单上验证数据,以便错误消息出现在表单本身而不是单独的页面上。 I currently have a check in my PHP code to query the database for an already existing email and kill the script and echo an error but it does so on another page. 我目前在我的PHP代码中进行检查,以查询数据库中已经存在的电子邮件,并杀死该脚本并回显错误,但这在另一页上进行。

Below is the code I have so far with the JavaScript validator in place. 下面是到目前为止我使用JavaScript验证器的代码。 I am still learning PHP and HTML so I'm lost as to what else I can try. 我仍在学习PHP和HTML,因此我迷失了其他尝试方法。 Can anyone help? 有人可以帮忙吗?

HTML CODE HTML代码

<!DOCTYPE HTML>
<html>
<head>
        <title>Registration</title>
        <script src="scripts/gen_validatorv4.js" type="text/javascript"></script>
</head>
<body>
    <div id="register">
        <fieldset style="width:30%"><legend>Registration Form</legend> <!-- Give the table a width of 30% and a title of Registration Form -->
            <table border="0"> <!-- Add border to table -->
            <tr>
            <form method="POST" action="registration.php" id="register"> <!-- Use POST to submit form data to registration.php -->
                <td>First Name</td><td> <input type="text" name="firstname" ></td> <!-- Input field for First Name -->
                </tr>
                <tr>
                <td>Last Name</td><td> <input type="text" name="lastname" ></td> <!-- Input field for Last Name -->
                </tr>
                <tr>
                <td>Address 1</td><td> <input type="text" name="address1" ></td> <!-- Input field for Address 1 -->
                </tr>
                <tr>
                <td>Address 2</td><td> <input type="text" name="address2"></td> <!-- Input field for Address 2 -->
                </tr>
                <tr>
                <td>City</td><td> <input type="text" name="city" ></td> <!-- Input field for City -->
                </tr>
                <tr>
                <td>State</td><td> <input type="text" name="state" ></td> <!-- Input field for State -->
                </tr>
                <tr>
                <td>Zip Code</td><td> <input type="text" name="zipcode" ></td> <!-- Input field for Zip Code -->
                </tr>
                <tr>
                <td>Phone Number</td><td> <input type="text" name="phonenumber" ></td> <!-- Input field for Phone Number -->
                </tr>
                <tr>
                <td>Email</td><td> <input type="text" name="email" ></td> <!-- Input field for Email -->
                </tr> 
                <tr>
                <td>Sign up to marketing emails?</td><td> <input type="radio" name="marketingaccept" value="yes"></td> <!-- Radio button to be checked if user wants to sign up for marketing emails -->
                </tr>
                <td><input id="button" type="submit" name="submit" value="Register"></td> <!-- Submit button -->
            </form>
            <script type="text/javascript">
            var frmvalidator  = new Validator("register");
            frmvalidator.EnableOnPageErrorDisplay();
            frmvalidator.EnableMsgsTogether();
            frmvalidator.addValidation("firstname","req","Please provide your first name");

            frmvalidator.addValidation("email","req","Please provide your email address");

            frmvalidator.addValidation("email","email","Please provide a valid email address");

            frmvalidator.addValidation("lastname","req","Please provide your last name");

            frmvalidator.addValidation("address","req","Please provide your address");
            </script>
            </tr>
            </table>
        </fieldset>
    </div>
</body>
</html>

PHP CODE PHP代码

<?php

define('DB_HOST', 'localhost'); // Define database host
define('DB_NAME', 'andrewha_fhsuproject1'); // Define database name
define('DB_USER','*******'); // Define database username
define('DB_PASSWORD','********'); // Define database password

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to host or present an error if connection fails
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to database or present an error if connection fails


function newregister() // Create function newregister()
{
    $firstname = trim($_POST['firstname']); // Grab data from the first name field and trim excess white space
    $lastname = trim($_POST['lastname']); // Grab data from the last name field and trim excess white space
    $address1 = trim($_POST['address1']); // Grab data from the address1 name field and trim excess white space
    $address2 = trim($_POST['address2']); // Grab data from the address2 name field and trim excess white space
    $city = trim($_POST['city']); // Grab data from the city field and trim excess white space
    $state = trim($_POST['state']); // Grab data from the state field and trim excess white space
    $zipcode = trim($_POST['zipcode']); // Grab data from the zipcode field and trim excess white space
    $phonenumber = trim($_POST['phonenumber']); // Grab data from the phonenumber field and trim excess white space
    $email = trim($_POST['email']); // Grab data from the email field and trim excess white space
    $marketingaccept =  $_POST['marketingaccept']; // Check to see whether the marketingaccept radio button is checked

    $sql="SELECT email FROM RegisteredUsers WHERE email='".$email."'"; // Look through existing emails to prevent duplication
    $resul=mysql_query($sql); // Perform above query
    $num = mysql_num_rows($resul); // Check above query to see if any rows match
    if ($num !=0){ // If a match is found...
        die("Sorry, you can only register once!.");  // ...the script is killed and an error is presented.
}   else // If no match is found, the script continues.
        $query = "INSERT INTO RegisteredUsers (firstname,lastname,address1,address2,city,state,zipcode,phonenumber,email,marketingaccept) VALUES ('$firstname','$lastname','$address1','$address2','$city','$state','$zipcode','$phonenumber','$email','$marketingaccept')"; // Create variable to insert  Grabbed data to database table and corresponding columns
        $data = mysql_query ($query)or die(mysql_error()); // Run above query or kill the script if an error is presented
    if($data) // Verify $data was run
    {
    header('Location: thankyou.html'); // Redirect to thankyou.html
    exit(); // End script
    }
}


if(isset($_POST['submit'])) // Check to see if submit button was hit...
{
    newregister(); // ...and go to newregister()
}
?>

I don't know if you underestimate or misunderstand the results of validation so forgive me if I am long winded here. 我不知道您是否低估或误解了验证的结果,因此,如果我在这里久违,请原谅我。

Your validation on the client is exactly that - it will only validate certain conditions are met on the client. 您在客户端上的验证完全是这样-它只会验证客户端上是否满足某些条件。 Once the data is sent to the server, without validation/sanitization, you risk someone tampering and thrashing your database, or worse. 一旦将数据发送到服务器而不进行验证/消毒,您就有可能有人篡改和破坏数据库,甚至更糟。

It would be possible for example to skip your client validation entirely and just enter an address in the address bar or via a script that would pretend to be a web browser sending data to your server. 例如,有可能完全跳过客户端验证,仅在地址栏中输入地址,或通过脚本伪装成将数据发送到服务器的Web浏览器。

The way your code is written above, the server will receive data and it can be engineered (rather easily) via a single input box to delete all the data in your database, or pending the server configuration, possible to destroy your server. 在上面的代码编写方式中,服务器将接收数据,并且可以通过单个输入框对其进行工程设计(相当容易),以删除数据库中的所有数据或挂起服务器配置,从而有可能破坏服务器。

An article elsewhere on stackoverflow should help discuss this subject in greater detail. 有关stackoverflow的其他文章应有助于更详细地讨论该主题。 I just did a quick search and found this one: What's the best method for sanitizing user input with PHP? 我只是进行了快速搜索,发现了这一点: 用PHP清理用户输入的最佳方法是什么? Read some of the answers. 阅读一些答案。

Now... with regards to validating your form data, I recommend you use jquery. 现在...关于验证表单数据,我建议您使用jquery。 It is a javascript add on library (meaning its entirely written in javascript) but it is cross browser compatible (there are variations in how javascript in some browsers handles data so your plain javascript might or might not work on all browsers. However code written in jquery will work in all browsers). 它是一个javascript附加库(表示其完全用javascript编写),但与跨浏览器兼容(某些浏览器中的javascript处理数据的方式有所不同,因此您的纯javascript可能在所有浏览器上都可能工作或可能不工作。 jQuery可以在所有浏览器中使用)。

The simplicity of validating your form data could be done by adding a 验证表单数据的简便性可以通过添加一个

class="required" class =“ required”

in to each input tag in your form. 进入表单中的每个输入标签。

Then, with jquery, you could perform something like the following 然后,使用jquery,您可以执行以下操作

// e will contain input field names of input tags that require but are missing data
var e=new Array();
// Get all input boxes with class "required", check the data input
// if the input length is less than one character in length, it
// will add the id tag to the "e" array.
$("input.required").each(function(){
if( $(this).val().length<1 )
{
    e.push( $(this).prop("id") );
}
});

// If e array has more than zero elements, it means more than zero input
// input tags are missing data and thus an alert is shown
if( e.length>0 )
{
 alert( "The following data fields are missing data:\n"+e.join(", ") );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM