1

I've been trying to set up something which will check an HTML form, to make sure that the text fields have at least 1 character entered, before the form is submitted (to the next page).

The HTML form is on one page, and flows through to a 2nd page. The 2nd page then updates a text file. That all works fine as is, so I dont want to change it. But what I do need is the validator.

I've searched and read through numerous suggestions, have seen some suggestions for using ISSET, and done the script below.

but this doesnt work (because the form is always submitted / there are no error messages). I have tired numerous other suggestions (based on other tutorials I have read). But it seems, that regardless of whether the text fields are empty or not, the form will still always submit. (there is a timestamp on the next page, so I can tell what gets submitted.

Can someone tell me whether Isset will work in this case? If so, where I am going wrong. Or if not, what I can use to get a validator for the text fields. I'd rather use PHP for this, but if I need to use Javascript that's a possibility.

(Added: I think the problem is that even if the below $error messages occur, it will never show up, because the page is automatically redirected via the submit button. What I need it similar to a event handler - eg, if button submit is clicked, check for errors. If there are errors, print them. If not, submit form. this code doesnt do that).

Page 1 code.

<?php
if (isset($_POST['submit'])) {
    $error = '';
    if (trim($_POST['topic']) == '') {
        $error = "Please enter a topic<br>");
    }
    if (trim($_POST['outline']) == '') {
        $error = "Please enter an outline<br>";
    }
    if ($error == '') {
        Echo "There are no errors";
    } else {
        echo "$error";
    }
}
?>
<form style="" method="post" action="addtopic2.php">
    Topic:<input name="topic" id="topicbox" maxlength="100" type="text">
    Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline">
</textarea><br><input name="submit" value="Submit" type="submit">
</form>

Page 2 code

 <?php
 $b = time (); 
 $c = date("g:i:s A D, F jS Y",$b);
 print "Topic and Outline Submitted at $c";

 $t = "Topic:";
 $o = "Outline:";
 $d = "Time Date:";

 $topic = $_POST['topic'];
 $outline = $_POST['outline'];

 $data = stripslashes("$t $topic | $o $outline | $d $c |\n");

 $fh = fopen("users.txt", "a");
 fwrite($fh, $data); 
 fclose($fh); 
 ?>
aljo f
  • 2,430
  • 20
  • 22
K Green
  • 129
  • 1
  • 4
  • 16

4 Answers4

1

Have you tried if((is_array($_POST)) && (!empty($_POST)) {...} ?

And it's better to use empty($var) instead $var == '' or !empty($var) instead $var != ''

Example:

<?php
    function arTrim (&$item , $keys) { //trims the string and makes it safe
        if (!is_array($item))
            $item = trim(htmlspecialchars($item));
    }

    array_walk($_POST, 'arTrim'); //apply this to each element in the our POST array


    if((is_array($_POST)) && (!empty($_POST)) {
        $error='';
        if((empty($_POST['topic'])) || (empty($_POST['password'])))
            $error='Please enter a topic<br / >';
        if((empty($_POST['outline'])) || (empty($_POST['password'])))
            $error='Please enter an outline<br />'; 
        if(empty($error)) 
            echo '<a href="addtopic2.php">text of the link</a>';
        else
            echo $error;
    }
?>

And dont't forget to use quotes when typing the key: $_POST['password'], $_POST['outline'] etc.

And one more advice: don't use double quotes in PHP without necessary. It's better to use the single one. Because all text in the double will be parsed for variables. Not optimised.

<br> is the wrong variant, use <br />. The same situation with <img />, <link />, <meta /> etc.

kpotehin
  • 1,025
  • 12
  • 21
  • no i havent tired it. how does that work? I need quite specific examples, as I only started learning PHP a few days ago – K Green Apr 12 '12 at 14:21
  • Should this be used on the same page as the html form, and the scrpt just inserted above it? And how will this stop the form from submitting to the next page, even if there are errors? – K Green Apr 12 '12 at 15:00
  • You should place the php code at the page you're indicated in the action attribute of your form. – kpotehin Apr 12 '12 at 15:05
  • Re "
    is the wrong variant, use
    ". Both just mean break line dont they? but
    is the HTMl version?
    – K Green Apr 12 '12 at 15:07
  • From what I read of that post, either are fine, but it depends on what else you are using. In this case I'm using strict HTML 4.01 and PHP (not my choice), and it has to pass the W3 checker.... (dont worry about posting your thoughts on W3 - I know). – K Green Apr 12 '12 at 15:20
1

This should do it

<?php

if(isset($_POST['submit'])){

    if($_POST['topic'] == ""){
        $error="Please enter a topic<br>"; 
    }

    if($_POST['outline'] == ""){
        $error="Please enter an outline<br>"; 
    }

    if(isset($error)){
        echo $error;
    }else{
        // Both fields have content in

    }

}


?>
<form style="" method="post" action="addtopic2.php">
Topic:<input name="topic" id="topicbox" maxlength="100" type="text">                
Outline: <textarea input wrap="nowrap" rows="10" cols="120" name="outline">
</textarea><br><input name="submit" value="Submit" type="submit">
</form>
user1061995
  • 80
  • 3
  • 10
  • Unfortunately not. Same problem as before. No errors are displayed, and the form submits as before. (With two blank fields where the text box text is entered, plus a timestamp). – K Green Apr 12 '12 at 15:14
  • I've edited my post - see the text under (Added), and the code is now separated between first and second page – K Green Apr 12 '12 at 16:23
  • If you haven't found the solution yet appologies I was away, you need to put your form verification on page 2 not page 1 – user1061995 Apr 17 '12 at 13:18
0

For starters, when validating data, always consider client-side validation (as in, Javascript) a nicety - you must always perform server-side validation (PHP) on the data.

PHP's isset() is designed to be used with string-type variables:

$password = trim($_POST['password']);
$topic = trim($_POST['topic']);
$outline = trim($_POST['outline']);

if(!isset($password)) {
    //is empty
}

PHP's empty() is designed to be used with arrays, and shouldn't be used to check string-type variables.

Source: Zackstronaut: Careful with PHP Empty()

Mattygabe
  • 1,772
  • 4
  • 23
  • 44
  • sorry, but im new to programming. Is a text field a string-type variable? Or are you suggestions i shouldnt use Isset at all? And are you suggesting I use something similar to the above script, in which case I'm not sure where I should be using it, or in what combination with other scripts. – K Green Apr 12 '12 at 14:50
  • In the example you provide, `password`, `topic` and `outline` would all be `string`s. In programming, any collection of text is considered a `string`, and in strongly-typed languages its usually a data type used for text. PHP is dynamic, and is not strongly typed, so most variables will be `string`s (if not, they're `array`s or an `object`) – Mattygabe Apr 12 '12 at 14:54
0

Javascript gives faster response, and if you're using HTML5 it can go even faster:

For html5 you could try something like:

<input type="text" id="topicbox" name="topic" required="required" data-minlength="6" />

For this to work on IE use this on header:

<!--[if lt IE 9]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

If you prefer javascript I'd suggest jquery plugin: jquery.validation

Palantir
  • 94
  • 1
  • 8