PHP - Why is this not NULL? Argh!

Associate
Joined
2 Nov 2007
Posts
488
This is driving me nuts. I would really appreciate some help before i pull my hair out. The bit that seems to be causing all the issues is:

Code:
if(!isset($error)) {

I cant see where the error is being set though?!

Full Code:

Code:
//If the form is submitted
if(isset($_POST['submit'])) {
	
	//Start the session
	session_start();
	
	//Set blacklists
	$badwords = "/(adult|beastial|bestial|blowjob|clit|cum|cunilingus|cunillingus|cunnilingus|****|ejaculate|felatio|fellatio|****|***|fuks|gangbang|gangbanged|gangbangs|hotsex|hardcode|jism|jiz|orgasim|orgasims|orgasm|orgasms|phonesex|phuk|phuq|porn|pussies|pussy|*****|xxx|viagra|phentermine|tramadol|adipex|advai|alprazolam|ambien|ambian|amoxicillin|antivert|blackjack|backgammon|texas|holdem|poker|carisoprodol|ciara|ciprofloxacin|debt|dating|porn|voyeur)/i";
	$exploits = "/(content-type|bcc:|cc:|document.cookie|onclick|onload|javascript)/i";
	$bots = "/(Indy|Blaiz|Java|libwww-perl|Python|OutfoxBot|User-Agent|PycURL|AlphaServer|T8Abot|Syntryx|WinHttp|WebBandit|nicebot)/i";
	
	//Check for any bots
	if(preg_match($bots, $_SERVER['HTTP_USER_AGENT'])) {
		die("<p>Spam bots are not allowed.</p>");
	}
	
	//Check to make sure that the name field is not empty, and that it does not contain badwords or exploits
	if(trim($_POST['contactname']) == '' ) {
		$error['contactname'] = "- You didn't enter your Full Name.<br>";
	} else if (preg_match($badwords, trim($_POST['contactname'])) !== 0 || preg_match($exploits, trim($_POST['contactname'])) !== 0) {
		$error['contactname'] = "- You entered a Full Name which contains unacceptable words.<br>";
	} else {
		$name = trim(stripslashes(strip_tags($_POST['contactname'])));
		$error['contactname'] = NULL;
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '') {
		$error['email'] = "- You didn't enter your Email address.<br>";
	} else if (!preg_match('/([a-z0-9])([-a-z0-9._])+([a-z0-9])\@([a-z0-9])([-a-z0-9_])+([a-z0-9])(\.([a-z0-9])([-a-z0-9_-])([a-z0-9])+)*/i', trim($_POST['email'])) || preg_match($badwords, trim($_POST['email'])) !== 0 || preg_match($exploits, trim($_POST['email'])) !== 0) {
		$error['email'] = "- You didn't enter a valid Email address.<br>";
	} else {
		$email = trim(stripslashes(strip_tags($_POST['email'])));
		$error['email'] = NULL;
	}

	//Check to make sure that the telephone number field is not empty
	if(trim($_POST['telephone']) == '') {
		$error['telephone'] = "- You did not enter your Telephone Number.<br>";
	} else if (preg_match($badwords, trim($_POST['telephone'])) !== 0 || preg_match($exploits, trim($_POST['telephone'])) !== 0) {
		$error['telephone'] = "- You entered a Telephone Number which is not valid.<br>";
	} else {
		$telephone = trim(stripslashes(strip_tags($_POST['telephone'])));
		$error['telephone'] = NULL;
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$error['message'] = "- You didn't enter a Message.<br>";
	} else if (preg_match($badwords, trim($_POST['message'])) !== 0 || preg_match($exploits, trim($_POST['message'])) !== 0) {
		$error['message'] = "- You entered a Message which contains unacceptable words.<br>";
	} else {
		$comments = trim(stripslashes(strip_tags($_POST['message'])));
		$error['message'] = NULL;
	}
	
	//Check if there are any errors
	if (!isset($error['contactname']) && !isset($error['email']) && !isset($error['telephone']) && !isset($error['message'])) {
		$error = NULL;
	}
	
	//If there is no error, send the email
	if(!isset($error)) {
	
		//Recipient email address
		$emailRecipient = '***@gmail.com'; 
		$emailTo = 'Company <'.$emailRecipient.'>'; 

		//Email subject
		$emailSubject = 'Enquiry';

		//Date
		date_default_timezone_set('Europe/London');
		$date = date('l, d F Y \a\t g:i A', time());

		//Customer callback?
		if ($_POST['checkbox'] == "1") {
			$requestCall = 'Yes';
		} else {
			$requestCall = 'No';
		}

		$callBack = 'Customer requests a call back? <strong>'.$requestCall.'</strong>';

		//Message
		$body = '
		<html>
		<head>
			<title>Enquiry</title>
			
			<style type="text/css">
			body {
			font-family:"Trebuchet MS", Tahoma, Verdana, Arial, Helvetica, sans-serif;
			color:#333;
			}
			
			h1 {
			text-align:center;
			font-weight:bold;
			}
			
			</style>
		</head>
		<body>
			<h1><b>Attention</b></h1>
			<p>You have received an enquiry, below, through your website contact form. The message was sent: <i>'.$date.'</i></p>
			<p>Name: <i>'.$name.'</i></p>
			<p>Email: <i>'.$email.'</i></p>
			<p>Telephone Number: <i>'.$telephone.'</i></p>
			<p>Comments:<br><i>'.$comments.'</i></p>
			<p>Call Back: <i>'.$callBack.'</i></p>
		</body>
		</html>
		';

		//To send HTML mail, the Content-type header must be set
		$headers = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

		//Additional headers
		$headers .= 'From: Thompson\'s East Africa Website <'.$emailRecipient.'>' . "\r\n";
		$headers .= 'Reply-To: '.$name.' <'.$email.'>' . "\r\n";
		$headers .= 'Return-Path: '.$name.' <'.$email.'>' . "\r\n";
		$headers .= 'X-Mailer: PHP/'.phpversion().'' . "\r\n";
		$headers .= 'X-Sender: '.$emailRecipient.'' . "\r\n";

		//reCaptcha
		require_once('recaptchalib.php');
		$privatekey = "**************";
		$resp = recaptcha_check_answer ($privatekey,
			$_SERVER["REMOTE_ADDR"],
			$_POST["recaptcha_challenge_field"],
			$_POST["recaptcha_response_field"]);
		if (!$resp->is_valid) {
			die ("The reCAPTCHA wasn't entered correctly. <a href =\"javascript:history.back()\">Please go back and try it again.</a>"
			);
		}

		//Send the message
		mail($emailTo, $emailSubject, $body, $headers);
		$emailSent = true;
	} 
	
	elseif (!is_null($error))
	{ echo "Error is null";
	}
}
?>

Cheers
 
You want unset($error);

With $error = null; $error is still set (so isset() == true) it's just set with a null value. PHP is one of the few languages that distinguishes between unset variables and variables set with a null value.
 
i don't get why you're creating an array with null values when there are no errors. if you didn't, you could just use is_array at the end to check if the $error array exists or not.
 
Thanks for the reply guys.

Moredhel: Where would i put the unset? I thought i could use isset with the value null, as acording to: http://php.net/manual/en/function.isset.php "Determine if a variable is set and is not NULL. "

whitecrook: Ill look into that.

marc2003: To be honest, i made all the code myself, apart from the errors bit which i inherited from an old form and adapted. Being a complete newbie to PHP i just went with it. Can you explain more fully what you would do?

By the way, i also tried using is_null and this still didnt work...

EDIT:

This works. My issue is i dont see why, or where, $error is being set. The code below just echos out "that worked", showing that $errors is null and not set:

Code:
<?php

$error['contactname'] = NULL;
$error['email'] = NULL;
$error['telephone'] = NULL;
$error['message'] = NULL;

if (!isset($error['contactname']) && !isset($error['email']) && !isset($error['telephone']) && !isset($error['message'])) {
		$error = NULL;
	}

if(!isset($error)) {
	echo "$error";
	echo "that worked";
	}

?>

Cheers
 
Last edited:
you are setting it right at the start. If it is null it is still considered 'set'. use is_empty to return 'false' if you want null to be considered 'empty'
 
marc2003: To be honest, i made all the code myself, apart from the errors bit which i inherited from an old form and adapted. Being a complete newbie to PHP i just went with it. Can you explain more fully what you would do?

on your validation, when something is successful, you're writing this....

PHP:
$error['message'] = NULL;

i'd omit this line of code altogether. then i'd replace this....

PHP:
	//Check if there are any errors
	if (!isset($error['contactname']) && !isset($error['email']) && !isset($error['telephone']) && !isset($error['message'])) {
		$error = NULL;
	}
	
	//If there is no error, send the email
	if(!isset($error)) {

with

PHP:
if(is_array($error)) {
  //display errors (preferably the form with existing fields populated with $_POST data to save the user from re-entering everything again)
} else {
 //process form
}

like i said, if you omit the creation of the $error array during the validation process (assuming everything is ok), then this simple if statement should work fine.
 
Thanks for the continued help. I see where you are coming from. But i dont see how you say i should not create an error array, but then in your code you check for one?

Very oddly, ive been trying to echo out all my variables as i go along to see what the problem is, i now have:

PHP:
	//Check if there are any errors
	if (!isset($error['contactname']) && !isset($error['email']) && !isset($error['telephone']) && !isset($error['message'])) {
		unset($error);
	} else {
		echo "contact name {$error['contactname']}<br>";
		echo "email {$error['email']}<br>";
		echo "telephone {$error['telephone']}<br>";
		echo "message {$error['message']}<br>";
	}

Which gives:

Code:
contact name
email - You didn't enter a valid Email address.

telephone
message
'Array' Error is not null

Is the regex the issue?

EDIT: No thinking though, regex is just doing its job as im using [email protected] to tab through the form. My bad.

Im starting to get extremely confused having all the code on one page, trying to think through the order in which the form is processed. While im here, would you reccomend me splitting into contact.php and process.php with somesort of contact.php?=sucess and failure?

Cheers again
 
Last edited:
But i dont see how you say i should not create an error array, but then in your code you check for one?

i said not to create the $error array when there are no errors. obviously if the validation discovers an $error - then create the array. that's why using is_array at the end is a very simple check.
 
In PHP, a variable is considered "set" if its name exists in the current scope; this will be the case even if its value is null. Furthermore, an array full of null values is not in fact null at all; it's an array (whose members happen to be null).
 
This is really confusing me, why does this show "not null":

Code:
<?php

error_reporting(E_ALL);

$error['contactname'] = NULL;
$error['email'] = NULL;
$error['telephone'] = NULL;
$error['message'] = NULL;

$errors = implode($error);
echo $errors;

if(is_null($errors)) {
	echo "is null is true";
} else {
	echo "not null";
}

?>
 
Thanks for the replies Mark. I appreciate you sticking with me. Im on the edge of throwing my computer out the window...

I tried getting rid of the array completely, as you seem to suggest, replacing them with new variables such as $errorEmail etc, however it then went completely wierd where the php validation just broke (allowing the $badwords), displaying a page with Email Sucessfully Sent and Email Sending Failed at once, and the sending an email with the invalid fields blank?!

Im now trying this:

Code:
	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$error['message'] = "- You didn't enter a Message.<br>";
	} else if (preg_match($badwords, trim($_POST['message'])) !== 0 || preg_match($exploits, trim($_POST['message'])) !== 0) {
		$error['message'] = "- You entered a Message which contains unacceptable words.<br>";
	} else {
		$comments = trim(stripslashes(strip_tags($_POST['message'])));
		unset($error['message']);
	}
	
	//Check if there are any error
	if (!isset($error['contactname']) && !isset($error['email']) && !isset($error['telephone']) && !isset($error['message'])) {
		$errors = NULL;
	}

	//If there are no error, send the email
	if(is_null($errors)) {

Which is going back to being ridicolous as before, ie:

Code:
Email Sending Failed!

Your message was not sent as the following errors have occured:

- You entered a Full Name which contains unacceptable words.
- You didn't enter a valid Email address.
Email Successfully Sent!

Thank you for contacting us! Your email was successfully sent and we will be in touch with you soon.

This is so frustrating! Its going to drive me mad!

Would it help if i showed you the full code / a live site complete with the form?
 
I tried getting rid of the array completely, as you seem to suggest,

um no i didn't. i said don't create an array called $errors when no errors are found. you should have left the other code intact to create the array when errors ARE FOUND. then a simple check at the end of validation using is_array would determine whether to send the mail or not.
 
Sorry for misunderstanding what you said. I am very new to all this...

Im now using:

PHP:
	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$error['message'] = "- You didn't enter a Message.<br>";
	} else if (preg_match($badwords, trim($_POST['message'])) !== 0 || preg_match($exploits, trim($_POST['message'])) !== 0) {
		$error['message'] = "- You entered a Message which contains unacceptable words.<br>";
	} else {
		$comments = trim(stripslashes(strip_tags($_POST['message'])));
		unset($error['message']);
	}
	

	//If there are no error, send the email
	if(!is_array($error)) {

//send the email

Which works on the php side, but now the captcha is broken?!

EDIT: My mistake, it seems now the captcha is processing after the PHP (it should validate before the form is sent to the sever. For example, i enter $badwords into the name, email and message and then leave the captcha blank / wrong. Form submits but comes back with PHP validation errors. BUT, enter sensible data that passes the PHP validation, leaving the captcha blank, form submits OK and then captcha says i have the code wrong?!)
 
Last edited:
why are you using unset there? :confused:

as for the captcha, never used it before but that code should also be part of your validation process. only attempt to send mail once it has passed.
 
Back
Top Bottom