2013-03-20 281 views
-3

我对PHP没有太多了解,并且制作了一个将数据发送到txt文件的简单表单。我的问题是,如果某些字段未填写,我无法弄清楚如何阻止提交表单。请有人指出我正确的方向吗?防止表单提交PHP

我也有一个简单的JavaScript,使得未填充的textareas红色,并警告用户填写正确的表单,但我不想允许提交,因为它仍然将值作为空发送到txt文件。

<?php      
    if(isset($_POST['button'])) { 
     $myFile = 'demo.txt'; 
     $titel = $_POST['filmnamn'] . ";" ; 
     $betyg = $_POST['betyg'] . ";" ; 
     $link = $_POST['link'] . ";" ; 
     $photo = $_POST['photo'] . ";" ; 
     $desc = $_POST['description'] . ";" ; 
     $data = "$titel$betyg$link$photo$desc"; 
     $fh = fopen($myFile, 'a'); 
     fwrite($fh, $data); 

     fclose($fh);       
} 
?> 
+0

您可以使用返回false停止submition – PSR 2013-03-20 14:51:44

+0

使用'javascript' validation – 2013-03-20 14:52:14

+0

如果输入是空的,你应该在你的表单的onsubmit事件上附加一个eventhandler,并设置一个'event.prefentDefault()'。 – ITroubs 2013-03-20 14:52:57

回答

2

你想要做的就是所谓的服务器端验证。 你应该做的是在任何事情之前测试你的变量。这会写我只有在filemnamn和betyg变量是不是空的文件:

  <?php      
       if(isset($_POST['button'])) { 
        if($_POST['filmnamn'] != "" && $_POST['betyg'] != "") { 
        $myFile = 'demo.txt'; 
        $titel = $_POST['filmnamn'] . ";" ; 
        $betyg = $_POST['betyg'] . ";" ; 
        $link = $_POST['link'] . ";" ; 
        $photo = $_POST['photo'] . ";" ; 
        $desc = $_POST['description'] . ";" ; 
        $data = "$titel$betyg$link$photo$desc"; 
        $fh = fopen($myFile, 'a'); 
        fwrite($fh, $data); 

        fclose($fh); 
       } 
       } 
      ?> 
+0

谢谢你的回答! – spovell 2013-03-20 15:10:13

+0

完美的作品:) – spovell 2013-03-20 15:30:39

4

要停止表单的提交,首先需要HTML和Javascript。所以基本上,你将一个函数链接到提交按钮,并且只在函数返回true时才提交。如果你http://phpmaster.com/form-validation-with-php/

<form action="..." method="post" onsubmit="return ValidatePage(this);"> 
<script type="text/javascript"> 

    function ValidatePage(form) { // the form itself is passed into the form variable. You can choose not to use it if you want. 
     // validating stuff. 
    } 

</script> 

此外,你需要服务器端验证,以防万一某人是JavaScript的一个挺举和曲折:

if (!$title1) { echo "there has been an error" } // alternatively to the '!$title1' you can use empty($title1), which is what I use more often and may work better. Another possible alternative is to use a variable that you set to true if an error has occurred, that way the bulk of your code can be at the beginning. 

else if... // repeat the if statement with else if for the remaining fields. 

else {...} // add the code to add to text file here. 

这里有一个更完整的例子向下滚动。另外,你应该知道,PHP中没有办法阻止表单从第一个地方提交,你所能做的就是让表单不“做”任何事情。

+1

客户端验证是为了用户舒适度(不向服务器往返),服务器端验证是为了数据完整性。所以最好至少在PhP中,最后用Javascript。 – 2013-03-20 14:56:40

+0

@Bartdude,哎呀!我没有阅读完整的问题。我以为他已经有了服务器端。我只是补充一点。 – 2013-03-20 14:57:37

+0

好吧,我几乎不知道任何PHP,并试图学习,我明白没有办法阻止它提交,但只要表单不发送任何我的需求得到满足,感谢您的答案! – spovell 2013-03-20 15:17:26

0
if (!$title1 || !$betyg || !$link || !$photo || !$desc) { 
//form + error message if blank 
} else { 
         $fh = fopen($myFile, 'a'); 
         fwrite($fh, $data); 
         fclose($fh);  
} 

以上只会验证所有领域,而不是单个