Simple php command not working? - php

I am following this tutorial on youtube on how to make a contact form (https://www.youtube.com/watch?v=9KS2QuFXIs8) and im at a part where some of my php code will not run because of ...
<?php else: ?>
<p>Thank you for your Message!</p>
<?php endif; ?>
also
<?php if($form_complete === FALSE): ?>
The rest of the code below that uses php works so im sure its not the server but maybe the fact the above code has a colon. Here's the rest of the code.
<?php
// Set email variables
$email_to = 'guomonster#gmail.com';
$email_subject = 'Form submission';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
<!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" xml:lang="en" lang="en">
<head>
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/contactform.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var nameError = '<?php echo $error_messages['fullname']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="formWrap">
<div id="form">
<?php if($form_complete === FALSE); ?>
<form>
<div class="row">
<div class="label">
Your Name
</div>
<div class="input">
<input type="text" name="fullname" id="fullname" class="detail" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" />
<?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
</div>
<div class="context">
e.g. John Smith
</div>
</div>
<div class="row">
<div class="label">
Your Email
</div>
<div class="input">
<input type="text" name="email" id="email" class="detail" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div>
<div class="context">
We will not share your email.
</div>
</div>
<div class="row">
<div class="label">
Your Message
</div>
<div class="input">
<textarea name="comment" id="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</div>
</div>
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send Message">
</form>
</div>
<?php else: ?>
<p>Thank you for your Message!</p>
<?php endif; ?>
</div>
</div>
</body>
</html>

In PHP You should use Brackets for conditional codeblocks.
<?php if ($form_complete === FALSE) { ?>
<p>if-branch</p>
<?php } else { ?>
<p>Thank you for your Message!</p>
<?php } ?>
But using PHP code inside html can be very confusing. Try the following:
<?php
if ($form_complete === FALSE) {
// do something
} else {
echo '<p>Thank you for your Message!</p>'
}
?>

Related

How to show an error message in each of different field for PHP Contact form?

I was following a tutorial and completed this contact form. It works fine, but I want to display a different message in each of the field instead of using a one box. I tried to move
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>"><?php echo $msg;?></div>
<?php endif; ?>
underneath the input field and that worked great as far as displaying in that spot, but it just shows the same message all at once. It does not show different message separately. How would I approach this from here?
body {
font-size:10px;
font-family:sans-serif, "Open-sans";
margin:0;
padding:0;
box-sizing:border-box;
letter-spacing:0.1rem;
}
.navbar {
background:#333;
width:100%;
}
.container {
max-width:1100px;
margin:auto;
}
.navbar-header {
display: flex;
flex-flow: row wrap;
justify-content: flex-start;
}
.navbar-brand {
font-size:1.5rem;
padding:1rem;
color:#fff;
text-decoration:none;
}
form {
font-size:1.3rem;
}
.form-group {
display:flex;
flex-direction: column;
margin:1.5rem;
}
label {
color:#333;
margin-bottom:0.7rem;
}
input, textarea {
max-width:100%;
border:0.5px solid darkslategray;
padding:1.3rem;
font-size:1.5rem;
}
button {
background:rgb(67, 130, 211);
color:#fff;
font-size:1.2rem;
padding:1rem;
margin:1.5rem;
border:none;
}
.alert {
margin:1.5rem;
padding:1.5rem;
font-size:1.5rem;
color:#fff;
}
.alert-danger {
background-color:rgb(219, 54, 48);
}
.alert-success {
background-color:rgb(28, 160, 39);
}
<?php
// Message Vars
$msg = '';
$msgClass = '';
// Check for submit
if(filter_has_var(INPUT_POST,'submit')){
// Get Form Data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Check Required Fields
if(!empty($email) && !empty($name) && !empty($message)){
// Passed
// Check Email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false ){
// Failed
$msg = 'Please use a valid email';
$msgClass = 'alert-danger';
} else {
// Passed
$toEmail = 'johnDoe#gmail.com';
$subject = 'Contact Request From '.$name;
$body = '<h2>Contact Request</h2>
<h4>Name</h4><p>' .$name. '</p>
<h4>Email</h4><p>' .$email. '</p>
<h4>Message</h4><p>' .$message.'</p>
';
// Email Headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-Type:text/html;charaset=UTF-8" . "\r\n";
// Additional Headers
$headers .= "From: " .$name. "<".$email.">". "\r\n";
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$msg = "Your email has been sent";
$msgClass = 'alert-success';
} else {
// Failed
$msg = "Your email was not sent";
$msgClass = 'alert-danger';
}
}
} else {
// Failed
$msg = 'Please fill in all fields';
$msgClass = 'alert-danger';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Contact US</title>
</head>
<body>
<nav class="navbar">
<div class="container">
<div class="navbar-header">
My Website
</div>
</div>
</nav>
<div class="container">
<?php if($msg != ''): ?>
<div class="alert <?php echo $msgClass; ?>"><?php echo $msg;?></div>
<?php endif; ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea name="message" class="form-control"><?php echo isset($_POST['message']) ? $message : ''; ?></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary">
Submit</button>
</form>
</div>
</body>
</html>
This is my current form.
I want to make it look like this one.
You can use the $msg variable as an array, instead of a string, to hold errors for specific fields.
<?php
$msg = [];
if(filter_has_var(INPUT_POST,'submit')){
//...
// Check Required Fields
if(!empty($email) && !empty($name) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false ){
$msg['email'] = [
'msg' => 'Please use a valid email'
'class' => 'alert-danger'
];
} else {
//...
if(mail($toEmail, $subject, $body, $headers)){
// Email Sent
$msg['default'] = [
'msg' => 'Your email has been sent'
'class' => 'alert-success'
];
} else {
// Failed
$msg['default'] = [
'msg' => 'Your email was not sent'
'class' => 'alert-danger'
];
}
}
} else {
// Failed
$msg['default'] = [
'msg' => 'Please fill in all fields'
'class' => 'alert-danger'
];
}
}
?>
And now in the HTML, you can check if the specific error or message exist and you display it at the right place; default messages at the top and email error under the email input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Contact US</title>
</head>
<body>
<nav class="navbar">
<div class="container">
<div class="navbar-header">
My Website
</div>
</div>
</nav>
<div class="container">
<!-- HERE -->
<?php if(isset($msg['default'])): ?>
<div class="alert <?php echo $msg['default']['class']; ?>"><?php echo $msg['default']['msg']?></div>
<?php endif; ?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<!-- ... -->
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? $email : ''; ?>">
<!-- AND HERE -->
<?php if(isset($msg['email'])): ?>
<div class="alert <?php echo $msg['email']['class']; ?>"><?php echo $msg['email']['msg']?></div>
<?php endif; ?>
</div>
<!-- ... -->
</form>
</div>
</body>
</html>
And you can actually do the same for any other input you want too.
You can store your validation warnings in an array type variable as opposed to a string.
For example, this line:
$msg = 'Please use a valid email';
You could instead do this:
$msg['email'] = 'Please use a valid email';
Also I think you want to verify if each of the required fields is present with its own individual if check, not all of them together, for example:
if(!empty($email) && !empty($name) && !empty($message)){
You can implement as:
if (empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$msg['email'] = 'Please use a valid email';
}
if (empty($name)) {
$msg['name'] = 'Please enter a name';
}
if (empty($message)) {
$msg['message'] = 'Please enter a message';
}
Then in your HTML section, below each of the relevant input fields, you can add:
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="<?php echo isset($_POST['name']) ? $name : ''; ?>">
<?php if(isset($msg['name'])): ?>
<p> <?php echo $msg['name']; ?>
<?php endif; ?>
</div>
However, in general I have to say this a very oldschool way of using PHP, where you would mix your logic code with your display code.
When you get the hang of it, perhaps you would like to study how Laravel, Symfony, or even CodeIgniter work, where you can use what known as MVC to separate your display from your logic.
As well, you can eventually use a templating engine like Blade or similar to echo out your variables.

The text of my web is garbled

I have used header("Content-Type:text/html; charset=utf-8"); & <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> on both html & php parts.
But for the webpage contents displayed , the text of the Chinese words are garbled .How to tackle the problem ?
create.php
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=utf-8");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Amount = "";
$CName_err = $Address_err = $Amount_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_CName = trim($_POST["CName"]);
if(empty($input_CName)){
$CName_err = "Please enter a name.";
} elseif(!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z'-.\s ]+$/")))){
$CName_err = 'Please enter a valid name.';
} else{
$CName = $input_CName;
}
// Validate address
$input_Address = trim($_POST["Address"]);
if(empty($input_Address)){
$Address_err = 'Please enter an address.';
} else{
$Address = $input_Address;
}
// Validate Amount
$input_Amount = trim($_POST["Amount"]);
if(empty($input_Amount)){
$Amount_err = "Please enter the amount.";
} elseif(!ctype_digit($input_Amount)){
$Amount_err = 'Please enter a positive integer value.';
} else{
$Amount = $input_Amount;
}
// Check input errors before inserting in database
if(empty($CName_err) && empty($Address_err) && empty($Amount_err)){
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Amount) VALUES (?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName,$Address,$Amount));
Database::disconnect();
header("Location: index.php");
}}
?>
<!DOCTYPE html>
<!--<html lang="en">-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>捐贈表格</h2>
</div>
<p>本人願意以信用卡捐款</p><br>
<p>I would like to make donation</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($CName_err)) ? 'has-error' : ''; ?>">
<label>Name</label>
<input type="text" name="CName" class="form-control" value="<?php echo $CName; ?>">
<span class="help-block"><?php echo $CName_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<textarea name="Address" class="form-control"><?php echo $Address; ?></textarea>
<span class="help-block"><?php echo $Address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($Amount_err)) ? 'has-error' : ''; ?>">
<label>Amount</label>
<input type="text" name="Amount" class="form-control" value="<?php echo $Amount; ?>">
<span class="help-block"><?php echo $Amount_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
<p>多謝您的支持</p><br>
<p>Thank you for your support</p>
</div>
</div>
</div>
</div>
</body>
</html>
Update
garbled page :

My call to a function is apparently incorrect, I know it's not, but it's not clear why

I'm trying a tutorial about making a private inbox feature, everything went well apart from the fact I get a 500 server error every time I try to press send. I have checked out the logs for what could be causing this error and here's what I received: PHP Fatal error: Call to undefined function fetch_users_id() in /apps/bla/web/inboxPage.php on line 17, referer: http://hinat.local/inboxPage.php
I have checked the function to see if anything is out of place, but cannot spot anything that could be throwing it off.
Would appreciate another pair of eyes to help me see what I have done wrong here.
Thanks in advance!
inboxPage.php:
<?php
if(isset($_POST['to'], $_POST['subject'], $_POST['body'])){
$errors = array();
if(empty($_POST['to'])){
$errors[] = 'You must enter at least one name.';
} else if (preg_match('#^[a-z, ]+$#i', $_POST['to']) === 0){
$errors[] = 'The list of names you gave does not look valid.';
} else {
$user_names = explode(',',$_POST['to']);
//Will remove and trailing spaces before and after name
foreach ($user_names as &$name){
$name = trim($name);
}
$user_id = fetch_users_id($user_names);
if(count($user_id) !== count($user_names)){
$errors[] = 'The following users could not be found: ' . implode(', ', array_diff($user_names, array_keys($user_id)));
}
}
if(empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
}
if(empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
if(empty($errors)){
}
}
if(isset($errors)){
//Form has been submitted but errors have occured
if(empty($errors)){
echo '<div class="msg success"> Your message has been sent! Return to your Inbox</div>';
//Form has been submittied and errors have occured
} else {
foreach ($errors as $errors) {
echo '<div class="msg error">', $errors, '</div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="site.css" >
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400" rel="stylesheet">
</head>
<body>
<!-- Header -->
<header class="primary-header container group">
<h1 class="logo">
<!-- <img src="../home/wendy/Pictures/Logo.png" alt="Website Logo"><br> -->
</h1>
<h3 class="tagline"> Cardiff, Wales </h3>
<nav class="nav primary-nav">
<ul>
<li>Home</li><!--
--><li>Login</li><!--
--><li>Register</li><!--
--><li>Tutors</li><!--
--><li>About Us</li><!--
--><li>Contact Us</li>
</ul>
</nav>
</header>
<form action="" method= "post">
<section class="row">
<div class="grid">
<div>
<label for="to">To</label>
<input type="text" name="to" id="to" value="<?php if (isset($_POST['to'])) echo htmlentities($_POST['to']); ?>" />
</div>
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) echo htmlentities($_POST['subject']); ?>" />
</div>
<div>
<textarea name="body" rows="20" cols="110"><?php if (isset($_POST['body'])) echo htmlentities($_POST['body']); ?></textarea>
</div>
<div>
<input type="submit" value="send" />
</div>
</div>
</section>
</form>
<footer class="primary-footer container group">
<small> ©</small>
<nav class="nav">
<ul>
<li>Home</li><!--
--><li>Login<!--
--><li>Tutors<!--
--><li>Register<!--
--><li>About Us<!--
--><li>Contact Us
</ul>
</nav>
</footer>
</body>
</html>
users.php:
<?php
function fetch_users_id($user_names){
foreach($user_names as &$name) {
$name = mysql_real_escape_string($name);
}
$results = mysql_query("SELECT id, Username FROM users WHERE Username IN ('" . implode("', '", $user_names) . "')");
$names = array();
while (($row = mysql_fetch_assoc($results)) !== false){
$names[$row['Username']] = $row['id'];
}
return $names;
}
?>
The function fetch_users_id does not exist in inboxPage.php
You must include or require users.php in inboxPage.php if you want to use that function within that file.
<?php
include("users.php");

Contact Form textarea deleting on Submission

I am working with on a contact form similar to the one shown by Dreamweaver Tutorial.
I have a followed his instructions fairly well except when it came to the CSS. However, after linking the form up to my site, I keep getting the validation error:
"Please enter your message to continue"
This occurs even after I have entered a message. I have gone through his 2-part series twice and have not been able to find an answer.
My code:
<?php
// Set email variables
$email_to = 'Matt#matthewbrianhawn.com';
$email_subject = 'Someone Contacted You on Your Site';
// Set required fields
$required_fields = array('name','email','comment');
// set error messages
$error_messages = array(
'name' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
<!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" xml:lang="en" lang="en">
<head>
<!-- Contact Form Designed by James Brand # dreamweavertutorial.co.uk -->
<!-- Covered under creative commons license - http://dreamweavertutorial.co.uk/permissions/contact-form-permissions.htm -->
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="contact/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var nameError = '<?php echo $error_messages['name']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="form-main">
<div id="form-div">
<?php if($form_complete === FALSE): ?>
<form class="form" id="form1" action="index.php" method="post">
<p class="name">
<input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" value="<?php echo isset($_POST['name'])? $_POST['name'] : ''; ?>" />
<?php if(in_array('name', $validation)): ?><span class="error"><?php echo $error_messages['name']; ?></span><?php endif; ?>
</p>
<p class="email">
<input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</p>
<p class="text">
<textarea name="text" class="feedback-input" id="comment" placeholder="Comment" ><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</p>
<div class="submit">
<input type="submit" value="SEND" id="button-blue" name="submit"/>
<div class="ease"></div>
</div>
</form>
<?php else: ?>
<div class="thanks_message">
<p>Thank you for your Message!</p>
</div>
<?php endif; ?>
</div>
</body>
</html>
In your text field definition for comment you have
textarea name="text" class="feedback-input" id="comment" placeholder="Comment"
id change it to
textarea name="comment" class="feedback-input" id="comment" placeholder="Comment"
Thats why it sees it as empty because currently its called "text" not "comment"
It's simply because the key 'comment' doesn't exist in your $_POST variable.
For instance the keys of your variable $_POST are the name of your input form.
Just try to replace 'comment' by the name of your field ('text') in your variable $error_messages

Where the heck do I put reCaptcha php on MY existing form?

I'm trying to implement reCaptcha into my existing contact form, and have hit a snag with where exactly (notice I used the word exactly) to place the server side PHP code within my page.
I've added the required PHP within the form with correct public key (and added the private key to the server side PHP).
I have the validation PHP for the form at the top of the same page as the form is on.
Existing validation code as follows:
<?php
// Set email variables
$email_to = 'myemailishere';
$email_subject = 'MY Enquiry TITLE IS HERE';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter your Name.',
'email' => 'Please enter a valid Email.',
'comment' => 'Please enter a Message.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
And my Form code is this:
<div id="mainform">
<?php if($form_complete === FALSE): ?>
<form autocomplete="off" action="index.php#contact" method="post" id="comments_form">
<div class="row">
<div class="label">Your full name</div><!---end label--->
<div class="input">
<input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your email address</div><!---end label--->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your number? (if you'd like a call)</div><!---end label--->
<div class="input">
<input type="text" id="telephone" class="detail" name="telephone" value="<?php echo isset($_POST['telephone'])? $_POST['telephone'] : ''; ?>" />
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your message</div><!---end label--->
<div class="input">
<textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Prove you're Human</div><!---end label--->
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // public key omitted for purpose of stackeroverflow
echo recaptcha_get_html($publickey);
?>
</div><!---end row--->
<div class="submit">
<input type="submit" id="submit" name="submit" value="SEND MESSAGE" />
</div><!---end submit--->
</form>
<?php else: ?>
<p>Thank you, we've received your message.</p>
<?php endif; ?>
</div><!---end mainform--->
So...where do I stick this code (as in integrate the code into my existing validation php)?????:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Hope that makes sense and someone can help?

Categories