PHP表单提交,验证变量

时间:2015-11-12 20:02:56

标签: php html forms

我挂了一个问题。我有一个html表单,没什么特别的。在提交时,我需要验证提交的值,如果它们失败,我需要返回到表单并指出错误。我以前做了很多次,但是通过简单的数据验证,比如空白输入字段或电子邮件地址格式。这里有很多验证,当我返回到我的表单时,它丢失了所有先前的输入。

这是我到目前为止所做的事情(有些事情目前可能会丢失,因为我经常调整它,但你会得到这个想法)

的index.php

    <div id="tabs-2">
    <center><h1>Add Event Form:</h2></center>
    <form name="htmlform" method="POST" action="htmlform.php">
        <table>
            <tr>
                <td class="left"><label for="first_name">Event Name *</label></td>
                <td><span><input type="text" name="event_name" value="<?PHP if(isset($_POST['event_name'])) echo htmlspecialchars($_POST['event_name']); ?>" required /></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Event Date *</label></td>
                <td><span><input id="datepicker" type="text" name="event_date" value="<?PHP if(isset($_POST['event_date'])) echo htmlspecialchars($_POST['event_date']); ?>" required /></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Start Time *</label></td>
                <td>
                    <span>
                        <select name="start_time" value="<?PHP if(isset($_POST['start_time'])) echo ($_POST['start_time']); ?>" required />
                        <?php
                            foreach($times as $time){
                                echo '<option value="' . $time . '">' . $time . '</option>';
                            }
                        ?>
                    </span>
                </td>
            </tr>
            <tr>
                <td class="left"><label for="first_name" >End Time *</label></td>
                <td>              
                    <span>
                        <select name="end_time" value="<?PHP if(isset($_POST['end_time'])) echo ($_POST['end_time']); ?>" required />
                        <?php
                            foreach($times as $time){
                                echo '<option value="' . $time . '">' . $time . '</option>';
                            }
                        ?>
                    </span>
                </td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Venue Name *</label></td>
                <td><span><input type="text" name="venue_name" value="<?PHP if(isset($_POST['venue_name'])) echo htmlspecialchars($_POST['venue_name']); ?>" required /></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Venue Address *</label></td>
                <td><span><input type="text" name="venue_address" value="<?PHP if(isset($_POST['venue_address'])) echo htmlspecialchars($_POST['venue_address']); ?>" required /></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Description</label></td>
                <td><span><textarea name="description" style="height: 150px; font-size: 13px;" value="<?PHP if(isset($_POST['description'])) echo htmlspecialchars($_POST['description']); ?>" required ></textarea></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Event URL *</label></td>
                <td><span><input type="text" name="event_url" value="<?PHP if(isset($_POST['event_url'])) echo htmlspecialchars($_POST['event_url']); ?>" required /></span></td>
            </tr>
            <tr>
                <td class="left"><label for="first_name">Event Image URL *</label></td>
                <td><span><input type="text" name="event_image" value="<?PHP if(isset($_POST['event_image'])) echo htmlspecialchars($_POST['event_image']); ?>" required /></span></td>
            </tr>
        </table>
        <p><input class="eventSub" type="submit" name="form_submit" value="Submit"></p>
        <br/>
    </form>
</div>

htmlform.php

<?php

    $event_name = $_POST['event_name'];
    $event_date = $_POST['event_date'];
    $start_time =  $_POST['start_time'];
    $end_time =  $_POST['end_time'];
    $venue_name = $_POST['venue_name'];
    $venue_address = $_POST['venue_address'];
    $description = $_POST['description'];
    $event_url = filter_var($_POST['event_url'], FILTER_SANITIZE_URL);
    $event_image = filter_var($_POST['event_image'], FILTER_SANITIZE_URL);

    $start = strtotime($start_time);
    $end = strtotime($end_time);

    if (filter_var($event_url, FILTER_VALIDATE_URL) === false) {
        //die(header("location:index.php?error=true&reason=url#tabs-2"));
    }

    if (filter_var($event_image, FILTER_VALIDATE_URL) === false) {
        //die(header("location:index.php?error=true&reason=url#tabs-2"));
    }

    if ($end < $start){
        $next_day_format = strtotime("+1 day", strtotime($event_date));
        $next_day = date("Y-m-d", $next_day_format);
        $json_start_time = $event_date . "T" . $start_time;
        $json_end_time = $next_day . "T" . $end_time;

    }
    else {
        $json_start_time = $event_date . "T" . $start_time;
        $json_end_time = $event_date . "T" . $end_time;
    }

    $cityclean = str_replace (" ", "+", $venue_address);
    $fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=true";
    $string = file_get_contents($fullurl); 
    $params = json_decode($string, true);

    $lon = $params['results'][0]['geometry']['location']['lng'];
    $address = substr($params['results'][0]['formatted_address'],0,-5);
    $lat = $params['results'][0]['geometry']['location']['lat'];
    $address_array = explode(',',$address);
    $state_zip = trim($address_array[2]);
    $sz_array = explode(' ',$state_zip);
    $state = $sz_array[0];
    $city = trim($address_array[1]);
    $zip = $sz_array[1];
?>

尚未完成。所有字段都经过验证后,理想情况会将提交发送到json格式化字符串。

问题是如果有任何验证失败我想重新加载提交表单的上一页但保留所有输入的值,截至目前,当它出错并重新加载页面时,表单是空白的。

3 个答案:

答案 0 :(得分:1)

完成此任务的最佳方法是使用Ajax。

1)。单击提交按钮后,立即通过Ajax将所有值提交到php文件,并从php文件中获取结果。

2)。如果php生成错误,则显示所需的错误。

3)。如果php没有生成任何错误,trigger表单将被提交。

这里有一些快速代码供您使用。

<script>
$("#form_submit").click(function(e) {
    e.preventDefault(); 
    $.ajax({
      type: "POST",
      url: "yourBackendFile.phps"
      data: $('#form').serialize(); //add an 'id' attribute to your form with id = "form"
    }).done(function( msg ) {      
        if(msg == 1)
        {
            //echo 1 from the php script if everything's fine.
            $("#form").trigger("submit"); //submit the form now
        }
        else
        {
            //show the 'msg' somewhere. Now this msg would contain all the errors that the php generated.
        }
});
});
</script>

答案 1 :(得分:0)

<强>更新

我不知道为什么这么长时间困扰我,这就是我完成我想要做的事情。

<强>的functions.php

<?php
    $event_name = $event_date = $start_time = $end_time = $venue_name = $venue_address = $description = $event_url = $event_image = "";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        //Checks if Event Name has been set
        if(empty($_POST['event_name'])){ 
            $error = 1; 
            $event_name_error_message = "Event Name Required";
        } 
        else { $event_name = $_POST['event_name']; }

        //Checks if an Event Date has been selected
        if(empty($_POST['event_date'])) { 
            $error = 1;
            $event_date_error_message = "Event Date Required";
        }
        else { $event_date = $_POST['event_date']; }

        //Checks if a Venue Name has been set
        if(empty($_POST['venue_name'])) { 
            $error = 1;
            $venue_name_error_message = "Venue Name Required";
        }
        else { $venue_name = $_POST['venue_name']; }

        //Checks if a Start Time has been selected
        if(empty($_POST['start_time'])) { 
            $error = 1;
            $start_time_error = "Start Time Required";
        }
        else { $start_time = $_POST['start_time']; }

        //Checks if an End Time has been selected
        if(empty($_POST['end_time'])) { 
            $error = 1;
            $end_time_error = "End Time Required";
        }
        else { $end_time = $_POST['end_time']; }

        //Checks if the Venue Address has been entered
        if(empty($_POST['venue_address'])) { 
            $error = 1;
            $venue_address_error_message = "Venue Address Required";
        }
        else { $venue_address = $_POST['venue_address']; }

        //Checks if a Description has been entered
        if(empty($_POST['description'])) { 
            $error = 1;
            $description_error_message = "Event Description Required";
        }
        else { $description = $_POST['description']; }

        //Check if an event URL has been entered.  Second condition checks if the URL is properly formated 
        if(empty($_POST['event_url'])) { 
            $event_url_error = "URL Required";
            $error = 1;
        }
        else { 
            $event_url = filter_var($_POST['event_url'], FILTER_SANITIZE_URL); 
             if (filter_var($event_url, FILTER_VALIDATE_URL) === false) {
                $event_url_error = "Event URL not properly formatted!";
                $error = 1;
             }
        }

        //Check if an event image URL has been entered.  Second condition checks if the URL is properly formated 
        if(empty($_POST['event_image'])) {
            $event_image_error = "URL Required";
            $error = 1;
        }
        else { 
            $event_image = filter_var($_POST['event_image'], FILTER_SANITIZE_URL);
            if (filter_var($event_image, FILTER_VALIDATE_URL) === false) {
                $event_image_error = "Event Image URL not properly formatted!";
                $error = 1;
            }
        }

        //Sets the end date to the following day if the end date time stamp is less than the start, assumes that an event which starts at 20:00 and ends at 02:00 has gone into the next day
        if(!isset($error)){
            //Converts the time stamps to a number which can be calculated
            $start_time =  $_POST['start_time'];
            $end_time =  $_POST['end_time'];
            $start = strtotime($start_time);
            $end = strtotime($end_time);

            if ($end < $start or $end == $start){
                $next_day_format = strtotime("+1 day", strtotime($event_date));
                $next_day = date("Y-m-d", $next_day_format);
                $json_start_time = $event_date . "T" . $start_time;
                $json_end_time = $next_day . "T" . $end_time;

            }
            else {
                $json_start_time = $event_date . "T" . $start_time;
                $json_end_time = $event_date . "T" . $end_time;
            }

            //Fills in missing info from the google map api so that a pin can be placed on the map for the event
            $cityclean = str_replace (" ", "+", $venue_address);
            $fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=true";
            $string = file_get_contents($fullurl); 
            $params = json_decode($string, true);

            $lon = $params['results'][0]['geometry']['location']['lng'];
            $address = substr($params['results'][0]['formatted_address'],0,-5);
            $lat = $params['results'][0]['geometry']['location']['lat'];
            $address_array = explode(',',$address);
            $state_zip = trim($address_array[2]);
            $sz_array = explode(' ',$state_zip);
            $state = $sz_array[0];
            $city = trim($address_array[1]);
            $zip = $sz_array[1];

            echo "Lon - $lon<br/>";
            echo "Name - $event_name<br/>";
            echo "State - $state<br/>";
            echo "Address - $address<br/>";
            echo "Lat - $lat<br/>";
            echo "City - $city<br/>";
            echo "Zip - $zip<br/>";
            echo "URL - $event_url<br/>";
            echo "Image URL - $event_image<br/>";
            echo "Start Time - $start_time<br/>";
            echo "End Time - $end_time<br/>";

            //Builds the completed json string which will then be submitted to the ant target
            $complete_json_string = '{"results":[{"venue":{"lon":"' . $lon . '","name":"' . $venue_name . '","state":"' . $state . '","address":"' . $address .'","lat":"' . $lat . '","city":"' . $city . '","zip":"' . $zip . '"},"start_time":"' . $json_start_time . '","end_time":"' . $json_end_time . '","event_url":"' . $event_url . '","description":"' . $description . '","name":"' . $event_name . '","image_url":"' . $event_image . '"}]}';

            echo $complete_json_string;
        }
    }
    if (empty($_POST["comment"])) { $comment = ""; }
    else {
        $cleaned = test_input($_POST["comment"]);
        $comment = ($_POST["comment"]);
    }

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

    $times=ARRAY('00:00:00','00:15:00','00:30:00','00:45:00','01:00:00','01:15:00','01:30:00','01:45:00','02:00:00','02:15:00','02:30:00','02:45:00','03:00:00','03:15:00','03:30:00','03:45:00','04:00:00','04:15:00','04:30:00','04:45:00','05:00:00','05:15:00','05:30:00','05:45:00','06:00:00','06:15:00','06:30:00','06:45:00','07:00:00','07:15:00','07:30:00','07:45:00','08:00:00','08:15:00','08:30:00','08:45:00','09:00:00','09:15:00','09:30:00','09:45:00','10:00:00','10:15:00','10:30:00','10:45:00','11:00:00','11:15:00','11:30:00','11:45:00','12:00:00','12:15:00','12:30:00','12:45:00','13:00:00','13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00','14:45:00','15:00:00','15:15:00','15:30:00','15:45:00','16:00:00','16:15:00','16:30:00','16:45:00','17:00:00','17:15:00','17:30:00','17:45:00','18:00:00','18:15:00','18:30:00','18:45:00','19:00:00','19:15:00','19:30:00','19:45:00','20:00:00','20:15:00','20:30:00','20:45:00','21:00:00','21:15:00','21:30:00','21:45:00','22:00:00','22:15:00','22:30:00','22:45:00','23:00:00','23:15:00','23:30:00','23:45:00','24:00:00');

    session_start();
?>

<强>的index.php

<?php require('scripts/functions.php');?>
<html>
    <head>
        <link rel="stylesheet" href="css/jquery-ui.css">
        <link rel="stylesheet" type="text/css" href="css/style.css"/>
        <script src="scripts/jquery.js"></script>
        <script src="scripts/jquery-ui.js"></script>
        <script language="javascript">
            function clearform() {
                document.getElementById("json").value="";
            }
        </script>
        <script>
            $(function() {
                $( "#tabs" ).tabs();
            });
            $(function() {
                $( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
            });
        </script>
        <title>Add Manual Event Data</title>
    </head>
    <body>
        <div id="tabs" class="body-check">
            <ul>
                <li><a href="#tabs-1">Event By String</a></li>
                <li><a href="#tabs-2">Add Event Form</a></li>
            </ul>
            <div id="tabs-1">
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    <center><h1>Add Event Data:</h1></center>
                    <p>
                        <textarea id="json" name="comment"><?php echo $comment;?></textarea>
                    </p>
                    <input type="submit" name="submit" value="Submit">
                </form>

                <?php
                    if (isset($cleaned)){
                        $_SESSION['json_string'] = $cleaned;
                        echo '<div id="ant"><iframe src="scripts/ant.php"></iframe></div>';
                    }
                ?>
            </div>
            <div id="tabs-2">
                <center><h1>Add Event Form:</h2></center>
                <form name="htmlform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . "#tabs-2";?>">
                    <table>
                        <tr>
                            <td class="left"><label for="first_name">Event Name *</label></td>
                            <td><span><input type="text" name="event_name" value="<?PHP if(isset($_POST['event_name'])) echo htmlspecialchars($_POST['event_name']); ?>" />
                            <?php if(isset($event_name_error_message)) echo "<span class='error'>$event_name_error_message</span>"; ?>
                            </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Event Date *</label></td>
                            <td><span><input id="datepicker" type="text" name="event_date" value="<?PHP if(isset($_POST['event_date'])) echo htmlspecialchars($_POST['event_date']); ?>" />
                            <?php if(isset($event_date_error_message)) echo "<span class='error'>$event_date_error_message</span>"; ?>
                            </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Start Time *</label></td>
                            <td>
                                <span>
                                    <select name="start_time">
                                        <option value="<?php echo $start_time;?>"><?php if(isset($_POST['start_time'])) { echo htmlspecialchars($_POST['start_time']); }?></option>
                                    <?php
                                        foreach($times as $time){
                                            echo '<option value="' . $time . '">' . $time . '</option>';
                                        }
                                    ?>
                                    </select>
                                    <?php if(isset($start_time_error)) echo "<span class='error'>$start_time_error</span>"; ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name" >End Time *</label></td>
                            <td>              
                                <span>
                                    <select name="end_time">
                                        <option value="<?php echo $end_time; ?>"><?PHP if(isset($_POST['end_time'])) { echo htmlspecialchars($_POST['end_time']); } ?></option>
                                    <?php
                                        foreach($times as $time){
                                            echo '<option value="' . $time . '">' . $time . '</option>';
                                        }
                                    ?>
                                    </select>
                                    <?php if(isset($end_time_error)) echo "<span class='error'>$end_time_error</span>"; ?>
                                </span>
                            </td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Venue Name *</label></td>
                            <td><span><input type="text" name="venue_name" value="<?PHP if(isset($_POST['venue_name'])) echo htmlspecialchars($_POST['venue_name']); ?>" />
                            <?php if(isset($venue_name_error_message)) echo "<span class='error'>$venue_name_error_message</span>"; ?>
                            </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Venue Address *</label></td>
                            <td><span><input type="text" name="venue_address" value="<?PHP if(isset($_POST['venue_address'])) echo htmlspecialchars($_POST['venue_address']); ?>" />
                            <?php if(isset($venue_address_error_message)) echo "<span class='error'>$venue_address_error_message</span>"; ?>
                            </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Description</label></td>
                            <td><span><textarea name="description" style="height: 150px; font-size: 13px;" ><?php if(isset($_POST['description'])) echo htmlspecialchars($_POST['description']); ?></textarea>
                            <?php if(isset($description_error_message)) echo "<span class='error'>$description_error_message</span>"; ?>
                            </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Event URL *</label></td>
                            <td><span><input type="text" name="event_url" value="<?php if(isset($_POST['event_url'])) echo htmlspecialchars($_POST['event_url']);?>" />
                            <?php if(isset($event_url_error)) echo "<span class='error'>$event_url_error</span>"; ?>
                             </span></td>
                        </tr>
                        <tr>
                            <td class="left"><label for="first_name">Event Image URL *</label></td>
                            <td><span><input type="text" name="event_image" value="<?PHP if(isset($_POST['event_image'])) echo htmlspecialchars($_POST['event_image']); ?>" />
                            <?php if(isset($event_image_error)) echo "<span class='error'>$event_image_error</span>"; ?>
                            </span></td>
                        </tr>
                    </table>
                    <p><input class="eventSub" type="submit" name="form_submit" value="Submit"></p>
                    <br/>
                </form>
            </div>
        </div>
    </body>
</html>

这样我的代码和索引就分开了。再次感谢。

答案 2 :(得分:-1)

看起来问题是表单操作是htmlform.php,因此当您提交表单时,您将发布到该PHP文件。这意味着您在index.php中尝试回显这些变量的PHP(例如echo htmlspecialchars($_POST['event_name']),根本无法访问它们。

你有几个选择

  • 您可以将表单处理逻辑从htmlform.php移到index.php中。然后,您可以访问$_POST数组以重新填充表单字段并显示错误。
  • 您可以使用AJAX将index.php中的表单字段中的值发布到htmlform.php,然后解析响应(可能使用JSON)以在表单字段中添加错误消息,同时仍保留用户的输入。网上有很多有用的教程可以帮助你做到这一点。