I require some assistance that I hope that one of you can answer for me. I have an assignment for my PHP course. For this assignment we were tasked with making a form with 4 input fields (including a reset and submit button). The fields are supposed to be labeled as name, address, email, and phone number. Now when I write the code into Dreamweaver I get no syntax errors but whenever I execute the script using Wamp, the form doesn't show. Any help would be appreciated as this is something that has to be done for our midterm.
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field. <br />\n";
++$errorCount;
$retval = "";
} else { //Only clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
function validateEmail ($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // Only Clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\. [[a-z]]{2,})$/i";
if (preg_match($pattern, $retval)==0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Address, $Phone) {
?>
<h2 style= "text-align:center">Contact Us</h2>
<form name="contact" action="contact_us.php" method="post">
<p>Your Name: <input type="text" name="Sender" value="<?php
echo $Sender; ?>" /> </p>
<p>Your E-mail: <input type="text" name="Email" value="<?php echo $Email; ?>" /></p>
<p>Address: <input type="text" name="Address" value="<?php echo $Address; ?>" /></p>
<p>Phone #: <input type="number" name="Phone" value="<?php echo $Phone; ?>"<br />
</p>
<p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Address = "";
$Phone = "";
if (isset($_POST['Submit'])) {
$Sender =
validateInput($_POST['Sender'], "Your Name");
$Email =
validateEmail($_POST['Email'], "Your E-mail");
$Subject =
validateInput($_POST['Address'], "Your Address");
$Message =
validateInput($_POST['Phone'],"Your number");
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Address, $Phone);
}
else {
$SenderAddress= "$Sender <$Email>";
$Headers= "From: $SenderAddress\nCC:
$SenderAddress\n";
// Substitute your own email address for // recipient#example.com
$result = mail ("recipient#example.com",
$Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " .
$Sender . ".</p>\n";
} ?>
You see nothing becouse you din`t call the function displayForm() you just create it.
so put this displayForm(); before the end of your php tag and see what will happen.
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Address, $Phone);
}
It looks like your form is set to only show when $ShowForm == TRUE && $errorCount > 0. Since your defaults are $ShowForm = TRUE and $errorCount = 0 your form will never show.
This is why using curly braces on your ifs, while making the file larger, help greatly when troubleshooting.
Related
I was doing an exercise from a book and copied exactly what was in there (to my knowledge) yet I still can't get it to process a valid E-Mail. I've tried different regular expressions but have had no luck. I'm pretty sure I missed something stupid (and sound pretty stupid asking for this but I am new to PHP). Can anyone take a look and see if you can see what I'm missing (or doing wrong)?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Me</title>
</head>
<header>
</header>
<body>
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else {
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
function validateEmail($data, $fieldName) {
global $errorCount;
if(empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else {
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" . "[\w-]+(\.[\w-]+)*" . "(\.[[a-z]]{2,})$/i";
if (preg_match($pattern, $retval)==0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Subject, $Message) {
?>
<h2 style = "text-align:center">Contact Me</h2>
<form name=contact: action="ContactForm.php" method="post">
<p>Your Name: <input type="text" name="Sender" value="<?php echo $Sender; ?>" /></p>
<p>Your E-mail: <input type="text" name="Email" value="<?php echo $Email; ?>" /></p>
<p>Subject: <input type="text" name="Subject" value="<?php echo $Subject; ?>" /></p>
<p>Message: <br />
<textarea name="Message"><?php echo $Message; ?></textarea></p>
<p><input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$showForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Subject = "";
$Message = "";
if (isset($_POST['Submit'])) {
$Sender = validateInput($_POST['Sender'], "Your Name");
$Email = validateEmail($_POST['Email'], "Your Email");
$Subject = validateInput($_POST['Subject'], "Subject");
$Message = validateInput($_POST['Message'], "Message");
if($errorCount==0)
$showForm = FALSE;
else
$showForm = TRUE;
}
if ($showForm == TRUE) {
if ($errorCount>0)
echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Subject, $Message);
}
else {
$SenderAddress = "$Sender <$Email>";
$Headers = "From: $SenderAddress\n CC: $SenderAddress\n";
$result = mail("greg.englar#gmail.com", $Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " . $Sender . ".</p>\n";
}
?>
</body>
</html>
I think I have a good grasp as to what the code is doing and how it is working but I am clearly missing something. It doesn't accept any E-Mail as valid and always shows an error message. For reference the book I'm using is "PHP Programming with MySQL Second Edition" by Don Gosselin.
There's an error in the regular expression. Should be [a-z] instead of [[a-z]] at the end
There must be thousands of questions asked about PHP email scripts but I still haven't found my answer. I looked on the php website but it didn't really help either.
Basically my script validates the inputs and displays error message accordingly but when I add the second part of the script to handle the sending of the email the page displays a 500 error. Here is my code. The email hasn't been set to the correct email at the moment but I know that's not the problem.
<?php include('includes/header.php');
$yourEmail = "hello#example.com";
$formSubject = "Message recieved from enquiry form";
if( isset( $_POST["submit"])) {
//Validate the data
function validateFormData( $formData ) {
$formData = trim( stripslashes(htmlspecialchars( $formData )));
return $formData;
}
//check to see if inputs are empty
// create variables with form data
// wrap the data with our function
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
} else {
$name = validateFormData( $_POST["name"]);
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
Code Works fine up until this point;
//Check to see if submit is set
//Check to make sure errors don't exist
//Send the email
// Redirect user to success.html
if ( isset( $_POST["submit"]) && (empty($emailError, $nameError, $enquiryError))) {
$to = $yourEmail;
$subject = $formSubject;
$headers = 'From:'. $name . "\r\n".
'Reply-To: '. $email . "\r\n".
'X-Mailer: PHP/' . phpversion();
$body =
'The person that contacted you was '.$name.'
Email: '.$email.'
URL: '.$url.'
Message: '.$enquiry.''.
mail($yourEmail, $formSubject, $body, $headers);
header("Location: success.html");
}
}
?>
This is the HTML form, which I'm sure is alright considering the PHP works up until a certain point and displays the error messages correctly. I know I have PHP_SELF which a lot of people say not to use but I want to to stay on the page if errors exist and only redirect if email has sent.
<form id="contactForm" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="name">Name <span class="asterisk">*</span></label>
<input type="text" name="name" id="name" value="<?php echo $name;?>"tabindex="1"/>
<span class="error"><?php echo $nameError; ?></span>
<label for="email">Email <span class="asterisk">*</span></label>
<input type="email" name="email" id="email" value="<?php echo $email;?>" tabindex="2"/>
<span class="error"><?php echo $emailError; ?></span>
<span class="error"><?php echo $emailValidError; ?></span>
<label for="url">Website</label>
<input type="url" name="url" id="url" value="<?php echo $url;?>" tabindex="3"/>
<h3>Tell us about your project </h3><br />
<textarea name="enquiry" id="enquiry" tabindex="4"><?php echo $enquiry;?></textarea>
<span class="error"><?php echo $enquiryError; ?></span>
<button type="submit" id="submit" name="submit" value="submit" >Submit</button>
</form>
Your problem is here:
empty($emailError, $nameError, $enquiryError)
empty accepts only one param, you are passing it 3. Change the conditional to:
if( isset( $_POST["submit"]) && ( empty($emailError) && empty($nameError) && empty($enquiryError) ))
Or if you want to shorten that conditional a little
$Errors = $emailError.$nameError.$enquiryError;
if( isset( $_POST["submit"] ) && empty( $Errors ) )
This is why there's an error. First syntax error and then (empty($emailError, $nameError, $enquiryError)) is not a good idea. I would do something like this:
$err=0;
if( !$_POST['name']) {
$nameError = "Please enter your name <br />";
$err++;
} else {
$name = validateFormData( $_POST["name"]);
$err++;
}
if( !$_POST['email'] || !preg_match("/^\S+#\S+$/", $email)) {
$emailError = "Please enter a valid email address <br />";
$err++;
} else {
$email = validateFormData( $_POST["email"]);
}
if( !$_POST['enquiry']) {
$enquiryError = "Please enter your enquiry <br />";
$err++;
} else {
$enquiry = validateFormData( $_POST["enquiry"]);
}
if ( isset( $_POST["submit"]) && $err==0) {
//your code here//
//and i would do like this//
$result_mail_send = mail($yourEmail, $formSubject, $body, $headers);
if($result_mail_send==true){
//redirect to success
}else{
//redirect to fail//
}
}
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I keep getting this syntax error for the line where the closing tag is and I can not for the life of me figure out what I did wrong. I thought I followed the instructions for my textbook for this assignment but I obviously didn't if I am getting an error. I must be blind because I can't spot the error. Any help would be greatly appreciated.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Contact Me</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field. <br />\n";
++$errorCount;
$retval = "";
} else { //Only clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
function validateEmail ($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // Only Clean up the input if it isn't // empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\. [[a-z]]{2,})$/i";
if (preg_match($pattern, $retval)==0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Subject, $Message) {
?>
<h2 style= "text-align:center">Contact Me</h2>
<form name="contact" action="ContactForm.php" method="post">
<p>Your Name: </p>
<p>Your E-mail:
<input type="text" name="Sender" value="<?php
echo $Sender; ?>" />
<input type="text" name="Email" value="<?php echo $Email; ?>" /></p>
<p>Subect: <input type="text" name="Subject" value="<?php echo $Subject; ?>" /></p>
<p>Message:<br />
</p>
<p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Subject = "";
$Message = "";
if (isset($_POST['Submit'])) {
$Sender =
validateInput($_POST['Sender'], "Your Name");
$Email =
validateEmail($_POST['Email'], "Your E-mail");
$Subject =
validateInput($_POST['Subject'], "Subject");
$Message =
validateInput($_POST['Message'],"Message");
if ($errorCount==0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Subject, $Message);
}
else {
$SenderAddress= "$Sender <$Email>";
$Headers= "From: $SenderAddress\nCC:
$SenderAddress\n";
// Substitute your own email address for // recipient#example.com
$result = mail ("recipient#example.com",
$Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " .
$Sender . ".</p>\n";
</body>
</html>
You are not closing the last else block
else {
$SenderAddress= "$Sender <$Email>";
$Headers= "From: $SenderAddress\nCC:
$SenderAddress\n";
// Substitute your own email address for // recipient#example.com
$result = mail ("recipient#example.com",
$Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " .
$Sender . ".</p>\n";
} ?>
There's a couple of things that I need some help on:
I have a function called isValid that is not checking if the emails entered in my form are valid?
How can i have my error messages display inside the form's text field?
Any help is greatly appreciated!
Below is my code:
<?php
//Set Variables to Empty String
$Email = " ";
$Subject = " ";
$Name = " ";
$Message = " ";
$error = " ";
if(isset($_POST['submit']) )
{
if (empty($_POST["Email"]))
{
$error = "** Enter a valid email";
}
else
{
$Email = isValid($_POST["Email"]);
}
if (empty($_POST["Subject"]))
{
$error = "** Enter a subject";
}
else
{
$Subject= test_input($_POST["Subject"]);
}
if (empty($_POST["Name"]))
{
$error = "** Enter your name";
}
else
{
$Name= test_input($_POST["Name"]);
}
if (empty($_POST["Message"]))
{
$error = "** Enter your message";
}
else
{
$Message= test_input($_POST["Message"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//isValid checks if email address is a valid one
function isValid($edata)
{
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]* [[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][ 0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $edata));
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><label>From (Email):</label></p>
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Subject:</label></p>
<input type="text" size="35" name="Subject">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Name:</label></p>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error;?></span>
<br><br>
<p><label>Message:</label></p>
<textarea type="text" cols="38" rows="6" name="Message"></textarea>
<span class="error"><?php echo $error;?></span>
<br><br>
<input type="submit" name="submit" value="submit">
<input type="reset" value="Reset">
</form>
<?php
if(empty($error))
{
// the email will be sent here
$to = "#gmail.com";
// the email subject
$subject = 'Message from XXXX website from: ' . $Name;
// the mail message
$msg .= "\r\nEmail: $Email";
$msg .= "\r\n\nSubject: $Subject";
$msg .= "\r\n\nName: $Name";
$msg .= "\r\n\nMessage: $Message";
mail($to, $subject, $msg, "From: $Email\r\nReply-To: $Email\r\nReturn-Path: $Email\r\n");
}
?>
<p>Thank you <b><?=$Name;?></b> for your message. Expect a response in 1 - 3 business days</p>
validate functions
<?php
$email_a = 'joe#example.com';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
?>
for second question, change your code like this:
if (empty($_POST["Email"]))
{
$error['Email'] = "** Enter a valid email";
}
.
.
.
if (empty($_POST["Name"]))
{
$error['Name'] = "** Enter your name";
}
.
.
.
<input type="text" size="35" name="Email">
<span class="error"><?php echo $error['Email'];?></span>
<input type="text" size="35" name="Name">
<span class="error"><?php echo $error['Name'];?></span>
Can someone tell me why this is not displaying the form? If I go to the address that I have it hosted on, the page just displays "Your message has been sent. Thank you, ." It seems to just execute and display the last function.
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // only clean up the input if it isn't empty
$retval = trim($data);
$retval = stripsplashes($retval);
}
return($retval);
}
function validateEmail($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // only clean up the input if it isn't empty
$retval = trim($data);
$retval = stripsplashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" . "[\w-]+(\.[\w-]+)*" . "(\.[[a-z]]{2,})$/i";
if (preg_match($pattern, $retval) == 0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Subject, $Message) {
?>
<h2 style = "text-align:center">Contact Me</h2>
<form name="contact" action="ContactForm.php" method="post">
<p>Your name: <input type="text" name="Sender" value="<?php echo $Sender; ?>" /></p>
<p>Your E-mail: <input type="text" name="Email" value="<?php echo $Sender; ?>" /></p>
<p>Subject: <input type="text" name="Subject" value="<?php echo $Subject; ?>" /></p>
<p>Message:<br />
<textarea name="Message"><?php echo $Message; ?></textarea></p>
<p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Subject = "";
$Message = "";
if (isset($_POST['Submit'])) {
$Sender = validateInput($_POST['Sender'],"Your Name");
$Email = validateInput($_POST['Email'],"Your E-mail");
$Subject = validateInput($_POST['Subject'],"Subject");
$Message = validateInput($_POST['Message'],"Message");
if ($errorCount == 0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE)
if ($errorCount>0) {// if there were errors
echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Subject, $Message);
} else {
$SenderAddress = "$Sender <$Email>";
$Headers = "From: $SenderAddress\nCC: $SenderAddress\n";
// Substitute your own e-mail address for recipient#example.com
$result = mail("recipient#example.com", $Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " . $Sender . ".</p>\n";
}
?>
You have:
$showForm = TRUE;
Which, when the form has not yet been submitted, will lead to the conditional statement always being true with $errorCount == 0. You don't call displayForm() in the else case of that conditional.
Hope this helps.
Ok, the error was because curly brace should've been after the if ($ShowForm == TRUE) instead of the if ($errorCount>0).