Log in

View Full Version : Understanding Undefined variable:



Webiter
06-07-2012, 02:24 PM
I wish to upgrade my ancient Contact Form to a new form as sample of which is positioned at .php here (http://www.validation.webitry.net/contact.php) and .html positioned here (http://www.validation.webitry.net/contact.html). It is however presenting a 500 error. What is the error advising of and what might be the resolve so that I can progress with the upgrade? The error log presents the following information on Undefined variables:

PHP Notice: Undefined variable: message_text in C:\wamp\www\PHP Validation\contact.php on line 75

<span class="message"><?php echo $message_text; ?></span>

PHP Notice: Undefined variable: errors in C:\wamp\www\PHP Validation\contact.php on line 76

<?php echo $errors; ?>

PHP Notice: Undefined variable: name in C:\wamp\www\PHP Validation\contact.php on line 80

<input type="text" name="name" class="textfield" value="<?php echo htmlentities($name); ?>" />

PHP Notice: Undefined variable: nameErr in C:\wamp\www\PHP Validation\contact.php on line 81

</label><br /><span class="errors"><?php echo $nameErr; ?></span></p>

PHP Notice: Undefined variable: email in C:\wamp\www\PHP Validation\contact.php on line 84

<input type="text" name="email" class="textfield" value="<?php echo htmlentities($email); ?>" />

PHP Notice: Undefined variable: emailErr in C:\wamp\www\PHP Validation\contact.php on line 85

</label><br /><span class="errors"><?php echo $emailErr ?></span></p>

PHP Notice: Undefined variable: message in C:\wamp\www\PHP Validation\contact.php on line 88

<textarea name="message" class="textarea" cols="45" rows="5"><?php echo htmlentities($message); ?></textarea>

PHP Notice: Undefined variable: messageErr in C:\wamp\www\PHP Validation\contact.php on line 89

</label><br /><span class="errors"><?php echo $messageErr ?></span></p>
The complete page contact.php is as follows:

<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
?>
<?php
// we must never forget to start the session
session_start();
?>

<?php
define("EMAIL", "xxxxxxxxx@xxx.xxx");

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

include('validate.class.php');

//assign post data to variables
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);

//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);

if(!$v->hasErrors()) {
$header = "From: $email\n" . "Reply-To: $email\n";
$subject = "Contact Form Subject";
$email_to = EMAIL;

$emailMessage = "Name: " . $name . "\n";
$emailMessage .= "Email: " . $email . "\n\n";
$emailMessage .= $message;

//use php's mail function to send the email
@mail($email_to, $subject ,$emailMessage ,$header );

//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");

} else {
//set the number of errors message
$message_text = $v->errorNumMessage();

//store the errors list in a variable
$errors = $v->displayErrors();

//get the individual error messages
$nameErr = $v->getError("name");
$emailErr = $v->getError("email");
$messageErr = $v->getError("message");
}//end error check
}// end isset
?>
<!--Form Handler Ends Here-->

<!--Form Starts Here-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow"/>
<title>Simple PHP Form Demo | Box Model Junkie</title>
<link rel="stylesheet" href="FormStyle.css" type="text/css" media="screen" />

</head>
<!--Form Construction Starts Here-->
<body>
<div id="contact_form_wrap">
<span class="message"><?php echo $message_text; ?></span>
<?php echo $errors; ?>
<?php if(isset($_GET['sent'])): ?><h2>Your message has been sent</h2><?php endif; ?>
<form id="contact_form" method="post" action=".">
<p><label>Name:<br />
<input type="text" name="name" class="textfield" value="<?php echo htmlentities($name); ?>" />
</label><br /><span class="errors"><?php echo $nameErr; ?></span></p>

<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="<?php echo htmlentities($email); ?>" />
</label><br /><span class="errors"><?php echo $emailErr ?></span></p>

<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"><?php echo htmlentities($message); ?></textarea>
</label><br /><span class="errors"><?php echo $messageErr ?></span></p>

<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
</div>

</body>
</html>

traq
06-07-2012, 07:38 PM
It means exactly what it said: those variables are undefined (don't exist).

All of those variables are being set inside a conditional block. If $_POST['submit'] is not set, then none of those other variables will be either. However, later, you try to use them outside of the conditional block (i.e., you always try to print them, even though they may or may not exist).

I couldn't tell you anything about the 500 error.
On your html page, however, you're trying to print PHP variables in your form (which, obviously, won't work as expected since it's not being parsed as PHP).

Webiter
06-16-2012, 05:03 PM
Have been around the houses with this in the past week. :o Having trouble breaking through and understanding the PHP lingo.

the experienced coder comments... "If $_POST['submit'] is not set", this may be a stupid question.... how might I set it ?

Thanks for the patients you guys show us juniors.

The .html file at the link is only there to show the form in the browser as the .php still throws a 500 error.

Nile
06-16-2012, 05:16 PM
Find:


<?php
define("EMAIL", "xxxxxxxxx@xxx.xxx");

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

And replace with:


<?php
define("EMAIL", "xxxxxxxxx@xxx.xxx");

$messageErr = "";
$message_text = "";
$errors = "";
$nameErr = "";
$emailErr = "";
$messageErr = "";

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

Webiter
06-16-2012, 07:46 PM
That worked a treat and also got rid of the 500 problem. :) Many Thanks for the pointer. I also had to define variables $name $email and $message to get rid of some other notices.

However, the form does not yet work as the tutorial sets out - ie working and showing the validation errors as they occur ! I confirm that the contact.php and the validate.class.php files are nor reaching each other by installing an echo statement line a follows:
echo 'Now inside validateStr'; die(); Is there anything in the validate.class.php file that needs editing to enable the include('validate.class.php'); to function ? :o

I show here the code for the file include('validate.class.php');


<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
?>
<?php
// we must never forget to start the session
session_start();
?>
<?php
class validate {

// ---------------------------------------------------------------------------
// paramaters
// ---------------------------------------------------------------------------

/**
* Array to hold the errors
*
* @access public
* @var array
*/
public $errors = array();

// ---------------------------------------------------------------------------
// validation methods
// ---------------------------------------------------------------------------

/**
* Validates a string
*
* @access public
* @param $postVal - the value of the $_POST request
* @param $postName - the name of the form element being validated
* @param $min - minimum string length
* @param $max - maximum string length
* @return void
*/
public function validateStr($postVal, $postName, $min = 5, $max = 500) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." must be at least {$min} characters long.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr

/**
* Validates an email address
*
* @access public
* @param $emailVal - the value of the $_POST request
* @param $emailName - the name of the email form element being validated
* @return void
*/
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, "Email Address Required");
} else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
$this->setError($emailName, "Valid Email Address Required");
}
}// end validateEmail

// ---------------------------------------------------------------------------
// error handling methods
// ---------------------------------------------------------------------------

/**
* sets an error message for a form element
*
* @access private
* @param string $element - name of the form element
* @param string $message - error message to be displayed
* @return void
*/
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError

/**
* returns the error of a single form element
*
* @access public
* @param string $elementName - name of the form element
* @return string
*/
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError

/**
* displays the errors as an html un-ordered list
*
* @access public
* @return string: A html list of the forms errors
*/
public function displayErrors() {
$errorsList = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errorsList .= "<li>". $value . "</li>\n";
}
$errorsList .= "</ul>\n";
return $errorsList;
}// end displayErrors

/**
* returns whether the form has errors
*
* @access public
* @return boolean
*/
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors

/**
* returns a string stating how many errors there were
*
* @access public
* @return void
*/
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = "There were " . count($this->errors) . " errors sending your message!\n";
} else {
$message = "There was an error sending your message!\n";
}
return $message;
}// end hasErrors

}// end class

Webiter
06-18-2012, 12:36 PM
Issue resolved

Find line in contact.php


<form id="contact_form" method="post" action=".">

and change to


<form id="contact_form" method="post" action="?">

Thanks to all for their assistance. It makes a nice form and validation. :)

ApacheTech
06-20-2012, 01:38 PM
All tutorial about PHP are available and many visitor are share their idea about topic.Here is really awesome .


Babelfish FAIL!