2013-03-20 279 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);  
} 

以上只會驗證所有領域,而不是單個