Question

I am trying to use PHP !isset and a function to check if the any fields submitted from a HTML form are empty, and if so kill (exit) the script. Only the code I have currently oddly skips right over my !issets and continues. +'s to anyone who can figure this out. :)

// Get fields from HTML form
$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Subject = $_POST["Subject"];
$Message = $_POST["Message"];

// Check to make sure no fields are empty
// If any fields are empty dumps script to fieldsmissing()
// If all fields are filled, continued to write actual email
if (!isset($Name)) {fieldsmissing(); };
if (!isset($Email)) {fieldsmissing(); };
if (!isset($Subject)) {fieldsmissing(); };
if (!isset($Message)) {fieldsmissing(); };

function fieldsmissing () {
exit;
}
Was it helpful?

Solution

isset just checks whether a variable is set and not null, not whether it's blank. Try something like:

if (!$Name) {fieldsmissing(); }
if (!$Email) {fieldsmissing(); }
if (!$Subject) {fieldsmissing(); }
if (!$Message) {fieldsmissing(); }

OTHER TIPS

function fieldsmissing () { // to declare before calling it
  exit;
}

// Get fields from HTML form
if (!isset($_POST["Name"])) {fieldsmissing(); };
if (!isset($_POST["Email"])) {fieldsmissing(); };
if (!isset($_POST["Subject"])) {fieldsmissing(); };
if (!isset($_POST["Message"])) {fieldsmissing(); };

$Name = $_POST["Name"];
$Email = $_POST["Email"];
$Subject = $_POST["Subject"];
$Message = $_POST["Message"];

// then use $Name etc...
php5 -r '$x="";if(isset($x)){print "isset\n";}'

returns:

isset

isset gives true for empty strings.

empty() can be much more useful. php.net/empty

$Name = $_POST["Name"]; will cause a warning if $_POST["Name"] is not available from the form.

You should probably do this instead:

$Name = ( isset( $_POST["Name"] ) ? $_POST["Name"] : '' );

if ( empty( $Name ) ) { fieldsmissing(); }

HTH

Don't use isset to check if filed was filled because it'll return true on empty string!

Instead use empty() function.

if (!isset($_POST['Name']) || empty($_POST['Name'])) {fieldsmissing(); }

Also, you don't have to use ; after }.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top