Form validation and (re)displaying help please

Hi all,

I’m a little bit confused as to why my form doesn’t behave as expected. The $errmsg never seems to display when a particular field has not been provided with a value, so I never get for example ‘You did not include a title’.

This form is very much incomplete still, but I just can’t see why the basic validation logic I’m going for doesn’t work.

Erm…why? Any thoughts very welcome. I may be missing something really stupid here.


<?php
/**
 *
 */

//Include configuration file first
require_once dirname(__FILE__). '/includes/config.inc.php';
	
//Include the language file set by config.inc.php
require_once $config['app_dir']. '/lang/' . $config['language'] . '.php';

//Include the functions file
require_once $config['app_dir']. '/includes/functions_inc.php';


/**
 * Establish a connection to the database.
 * We can use the config values defined in config.php as arguments for the class
 */
 require ('classes/dbutility.class.php');
 //Instantiate the dbutility class.  Connects to db instantly using config credentials
 $db = new dbUtil($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);



/**
 * Page processing
 */

$title = $lang['upload_title'];
$heading = $lang['upload_heading'];
$description = $lang['upload_description'];

$pagelink = '"index.php">Thumbs Gallery';

include_once $config['app_dir']. '/includes/xhtml_headnav.html';

//Setup defaults for form processing
$clean = array();
$errors = 0;


//VALIDATE FORM ENTRIES
if (isset($_POST['submit'])) {
	
	$errmsg = '';
	
	
	if (isset($_POST['title'])) {
		//validate title
		$is_title_valid = validateTitle($_POST['title']);
		
		if ($is_title_valid === TRUE){
			$clean['title'] = htmlentities($_POST['title']);
		} else {
			$errors++;
			$errmsg .= 'Title must be no longer than 100 characters';
		}
		
	} else {
		$errors++;
		$errmsg .= 'You did not include a title';
	}
	
	if (isset($_POST['description'])) {
		//validate description
		$is_description_valid = validateDescription($_POST['description']);
		
		if ($is_description_valid === TRUE){
			$clean['description'] = htmlentities($_POST['description']);
		} else {
			$errors++;
			$errmsg .= 'Description must be between 10 and 255 characters';
		}
	} else {
		$errors++;
		$errmsg .= 'You did not provide a description';
	}
	
	if (isset($_POST['userfile'])) {
		//validate image upload
		/*
		 * Check the file is a jpeg image that has definately been provided by the form, see hoe-ans_uploading_files
		 */
	} else {
		$errors++;
		$errmsg .= 'You have not included a file to upload';
	}
	
}
//Ready to render page, so we initilise the output variable
	$output = '';
	
//If form is submitted with no errors ACTION DATA
if (isset($_POST['submit']) && $errors == 0) {
	//place tile, description and path into the table, then upload image
	
	
	$output .= '<p>Your image has been uploaded.</p>';
	//after data has been processed, close db connection END OF PROCESSING
	$db->close();
	
} else {
	
	//(Re)display the upload form
	$output .='
	<form enctype="multipart/form-data" action="' .$_SERVER['PHP_SELF']. '" method="post">
		<fieldset>
		<div>
			<label for="ttl">Title</label>
			<input type="text" name="title" id="ttl" size="40" value="' .(isset($clean['title']) ? htmlentities($clean['title']) : ''). '"/>
		</div>
		<div>	
			<label for="desc">Description</label>
			<textarea name="description" id="desc" rows="5" cols="30">' .(isset($clean['description']) ? htmlentities($clean['description']) : ''). '</textarea>
		</div>
		<div>
			<label>Upload Image Location</label>
			<input name="userfile" type="file"/>
		</div>
		<div>
			<input type="submit" value="Submit Image" name="submit"/>
		</div>
		</fieldset>
	</form>'."\
";
	
	//Any errors should be displayed to the user also
	if ($errors > 0) {
		//If errors found, display these to user
		$output .= '<p>Errors in your submission: ' .$errmsg. '</p>'. "\
";
	}
} //close the final else statement

//Echo the generated xhtml
echo $output;

//Include the html footer to end the page
include_once $config['app_dir']. '/includes/xhtml_footer.html';

?>

so I never get for example ‘You did not include a title’.

What do you get?

You could try to put some echo statements in your code to check the values of certain variables at certain points in the code, and to check the flow.

Even if I don’t provide a value in the ‘title’ field on the form, when clicking submit, the $errmsg provided comes out as ‘Title must no longer than 100 characters’. So the else statement from if (isset($_POST[‘title’])) , doesn’t seem to ever be triggered. The same seems to apply for the ‘description’ entry too.

My guess is that the validateTitle() function returns FALSE (or a value different from TRUE) when the title is 0 characters as well. If you want to show different error messages, your validateTitle() function should return different values (or return the error messages directly).

Well surely the function isn’t even called unless there is a value in the field in the first place, or am I misunderstanding the use of isset?

In any case here are the functions I’m calling to check the fields.


function validateTitle($title) {
 	//Remove whitespace
 	$title = trim($title);
	
	//Get the length of the string
	$length = strlen($title);
	
	//Check it is within limits
	if($length >= 1 && $length <= 100  ) {
		return true;
	} else {
		return false;
	}
 }

 function validateDescription($description) {
 	//Remove whitespace
 	$description = trim($description);
	
	//Get the length of the string
	$length = strlen($description);
	
	//Check it is within limits
	if ($length >= 10 && $length <= 256) {
		return true;
	} else {
		return false;
	}
 }

Your code seems unnecessarily complicated. e.g.


	if (isset($_POST['title'])) {
		//validate title
		$is_title_valid = validateTitle($_POST['title']);
		
		if ($is_title_valid === TRUE){
			$clean['title'] = htmlentities($_POST['title']);
		} else {
			$errors++;
			$errmsg .= 'Title must be no longer than 100 characters';
		}
		
	} else {
		$errors++;
		$errmsg .= 'You did not include a title';
	}

Could be:


$errmsg = '';

// later ...

if ( !isset($_POST['title']) || validateTitle($_POST['title']) === false ){
$errmsg .= " You must add a Title which is no longer than 100 chars. ";
}

// later ...

if ($errmsg !== ''){
echo $errmsg;
}

EDIT
The existence of anything other than an empty string in $errmsg performs the same function as checking that the count of errors is greater than 0, doesn’t it?

Surely, but apparently for some reason it is called. That’s why I suggested to add echo statements (or var_dump or whatever) to check the flow and the values of certain variables (like for example $_POST[‘title’]).

After using var_dump to check the $_POST values after clicking ‘submit’ I saw that values were declared as strings with a length of 0 if a field was left empty. This wasn’t what I expected to see but I’m really quite new to PHP still. So I altered from using isset to strlen. For example:


if ((strlen($_POST['title'])) == 0) {
	$errors++;
	$errmsg .= 'You did not include a title';
		
} else {
    //validate title input

}

This method has allowed me to provide different error messages just as I would have originally expected from the use of isset. I’m confused but pushing forwards now.

For Cups - Yes you are indeed correct. I’m not great at writing efficient code at all, but also I thought an error count might be handy at some point for user feedback.

Thanks for suggestions on this issue.

Perhaps you need to declare $errors and $errmsg as globals in your validation script?