contact form not giving data - php

I have issue with fat-free contact form.
My contact form does nothing. Like no success or any kind of error data.
My contact form POST and GET route:
$f3->route('GET #contact: /contact', 'Rimtay\Client->GET_Contact');
$f3->route('POST #contact: /send', 'Rimtay\Client->contactPost');
My contact form POST function:
function contactPost(){
function validateInput($data) {
$bad = array("content-type","bcc:","to:","cc:","href");
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
foreach ($bad as $badString) {
if (preg_match('/('.$badString.')/i',$data)) {
// If it looks like someone is trying to hack
// into the site via the contact page, then just stop.
exit;
}
}
return $data;
}
// define variables and set to empty values
$contactNameError = $contactEmailError = $contactMessageError = "";
$name = $email = $message = $success = "";
if ($f3->exists('POST.name',$name)) {
if ($name !== '') {
$name = validateInput($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$contactNameError = "Wrong name";
} else { // valid name
$f3->set('contactName',$name);
}
} else {
$contactNameError = "name empty";
}
} else {
$contactNameError = "name error";
}
if ($f3->exists('POST.email',$email)) {
if ($email !== '') {
$email = validateInput($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailError = "wrong email";
} else { // valid email
$f3->set('contactEmail',$email);
}
} else {
$contactEmailError = "email empty";
}
} else {
$contactEmailError = "error email";
}
if ($f3->exists('POST.subject',$message)) {
if ($message !== '') {
$f3->set('contactMessage',$message);
} else {
$contactMessageError = "message tühi";
}
} else {
$contactMessageError = "lambi message";
}
if (($contactNameError === '') && ($contactEmailError === '') && ($contactMessageError === '')) {
// send the message
$messageBody = "";
unset($_POST['submit']);
$messageBody = "Name: ".$name."\n";
$messageBody .= "email: ".$email."\n";
$messageBody .= "Subject: Construction - Message from " . $name."\n";
$messageBody .= $message."\n";
$messageBody = wordwrap($messageBody,70);
$to = $f3->get('contactAddresses');
$subject = 'Contact Submitted';
if (mail($to, $subject, $messageBody)){
$f3->set('contactSuccess',true);
} else {
// error sending the email to myself
}
} else {
$f3->set('contactSuccess',false);
}
// Set the content source
$this->f3->set('pageContent','contact.html');
}
my form looks like this:
<form class="form" action="{{ #schemeHost.#PATH }}" method="post">
<textarea class="textarea" name="message" placeholder="Message*">{{ #contactMessage }}</textarea>
<div>
<input type="text" placeholder="Name *" name="name" value="{{ #contactName }}" class="input">
<input type="email" placeholder="Email *" name="email" value="{{ #contactEmail }}" class="input">
</div>
<button class="submit" type="submit" name="submit">Send</button>
</form>
My System isnt giving any success or error messages.
And not sending out contact form messages to email.
I dont see what I'm doing wrong there.

Your code is very prone to errors. For example, the $f3 variable is not defined anywhere in your code.
How does your code handle the errors? It might be that you see no errors because there is no error reporting setup by you and the server is silently not showing the errors. I suggest you to check the error log.
I also suggest to use a form validation library like CakePHP validation library. You will need to learn how to use it, but it will save you big time in the end and your code will be cleaner.

Related

How to validate the textbox inside echo?

I'm trying that validating the text box inside echo in php. I tried some methods but it is not working.
php form code:
echo '<form method="post" action="singlepage.php?id='.$idn.'"';
echo '<label id="blogtextarea2">Comment:</label><textarea rows="10" cols="75" name="comment" id="blogtextarea" ></textarea><br>';
echo '<input type="submit" name="post" id="blogsubmit" value="post">';
echo '</form>';
and validation code is
if(isset($_POST['post']))
{
if ($_POST['comment'] != "") {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
if ($_POST['comment'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors= 'Please enter your name.<br/>';
}
}
I'm not exactly sure what you meant by "not working", but I have cleaned up your code and changed the check for an empty POST comment data using the empty() function instead.
There was also a redundant check within your first check for an empty comment which I've removed:
$errors = '';
if(isset($_POST['post'])) {
if(!empty($_POST['comment'])) {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
} else {
$errors = 'Please enter your name.<br/>';
}
}
echo $errors;
Ok found it why it is not working
if(isset($_POST['post']))
{
if (!empty($_POST['comment'])) {
$_POST['comment'] = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
} else {
$errors = 'Please enter your name.';
}
}
echo $errors;
You have to check defined conditions on singlepage.php

PHP - Form validation functions. How to use functions to write better code?

I'm practicing doing simple form validation and have come unstuck trying to use a function to replace code that I repeat several times throughout the validation script.
I am trying to write a function that saves an error message to an $errors array when validation fails for that form field.
The function I'm using does not return any error messages but does not display the message that is should do when validation fails.
I'm testing it on just one filed, the username field and with just one validation rule, username cannot be blank.
NB/ The form and validation worked when I was not trying to use a function.
Here is what I have, what a I doing wrong? I'm struggling to get to grips with functions :-(
functions.php
<?php
//Function to deal with saving error messages to errors array
// #param - 2 parameters. Name of field that has the error; Error message string
// #return - an error message string
function errorHandler($errField, $errMsg){
$errors[$errField] = $errMsg;
return $errors;
}
index.php
<?php
include_once '_includes/headers.php';
include_once '_includes/functions.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Initialize variables
$data = array();//Store cleaned valid data for output
$errors = array();//Store error messages
$form_is_submitted = false;
$errors_detected = false;
if(isset($_POST['registerBtn'])){
$form_is_submitted = true;
//VALIDATE FORM
//Validate - Username
if (isset($_POST['username'])) {
$username = trim($_POST['username']);
//Username cannot be blank - validation
if($username !== ''){
$data['username'] = htmlentities($username);
//Get the length of the string
$stringLength = strlen($username);
//Username minimum 5 maximum 15 characters long - validation
if($stringLength < 5 || $stringLength > 15){
$errors_detected = true;
$errors['username'] = ' Invalid length. Must be between 5 - 15 characters!';
}else {
$data['username'] = htmlentities($username);
}
//Username must only be alphanumeric characters - validation
if(!ctype_alnum($username)){
$errors_detected = true;
$errors['username'] = ' Invalid characters. Alphanumeric characters only!';
}else {
$data['username'] = htmlentities($username);
}
}else {
$errors_detected = true;
//Call error message function
if($errors_detected === true){
errorHandler('username', ' Field cannot be blank!');
}
}
}else {
$errors_detected = true;
$errors['username'] = ' Is not set!';
}
//Validate - Email
if(isset($_POST['email'])){
$email = trim($_POST['email']);
//Email cannot be blank - validation
if($email !== ''){
$data['email'] = htmlentities($email);
//Email must be valid format - validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors_detected = true;
$errors['email'] = ' Invalid email format!';
}else {
$data['email'] = htmlentities($email);
}
}else{
$errors_detected = true;
$errors['email'] = ' Email address is required!';
}
}else {
$errors_detected = true;
$errors['email'] = " is not set!";
}
}
//Declare form output variable
$output = '';
//IF VALID SUBMISSION
if($form_is_submitted === true && $errors_detected === false){
$output .= '<h3>Form successfully submitted</h3>';
echo $output;
foreach($data as $keys => $values){
echo "<p>$keys : $values</p>";
}
} else {
//IF INVALID SUBMISSION
if($errors_detected === true){
$output .= '<h2>There are errors on the form</h2>';
echo $output;
foreach($errors as $key => $value){
echo "<p>" . htmlentities($key) . ':' . htmlentities($value) . "</p>";
}
}
//DISPLAY/REDISPLAY FORM
$self = htmlentities($_SERVER['PHP_SELF']);
$output ='
<form action="'. $self .'" method="post">
<fieldset id="registration">
<legend>Register</legend>
<p>Insert your profile information:</p>
<div>
<label for="username">Username</label>
<input id="username" name="username" type=text value="' . (isset($data['username']) ? $data['username'] : '') . '" />
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type=email value="' . (isset($data['email']) ? $data['email'] : '') . '" />
</div>
<input type="submit" id="registerBtn" name="registerBtn" value="Register" />
</fieldset>
</form>
';
echo $output;
}
?>
<?php
include_once '_includes/footers.php';
?>
UPDATE:
I have updated my function to use the $errors array in my function. This should now no longer be a scope issue I think. As per Francesco Malatesta below ...
First of all, you should study something about objects, classes, exceptions and more complex stuff for this kind of job. I am assuming you want to learn about functions and do some practice.
You should, first of all, pass the errors array as a parameter.
Like this:
function errorHandler($errorsArray, $errField, $errMsg){
$errorsArray[$errField] = $errMsg;
return $errorsArray;
}
And then, in your index.php file:
errorHandler($errors, 'username', ' Field cannot be blank!');
This should work, because you must use the $errors array in your function. It's a scope-related problem.
However, after this, forget everything (well, not everything) and study OOP and Exceptions :)
Have you heard about Exceptions?
Simple example to use a exception:
<?php
try {
// your if's
if(40 > 30) {
throw new Exception("40 is a bigger");
}
} catch (Exception $error) {
echo 'Your error is: '.$error->getMessage();
}
?>

Wordpress Help Redirect after form submission

I want to have my contact form redirect after form submission. I don't know how do it. This is my code and also it's giving me an error.
<?php
// If the form is submitted
if(isset($_POST['submit'])) {
// Include WordPress Core Functions
$wp_include = '../wp-load.php';
while(!#include_once($wp_include)) { $wp_include = '../'.$wp_include; }
//
// Field Validation
//
// Check to make sure that the name field is not empty
if(trim($_POST['cf_name']) == '') {
$has_error = true;
}
else {
$name = trim($_POST['cf_name']);
}
// Check to make sure that the subject field is not empty
if(trim($_POST['cf_subject']) == '') {
$has_error = true;
}
else {
$subject = trim($_POST['cf_subject']);
}
// Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$has_error = true;
}
elseif(!preg_match("/^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$/i", trim($_POST['email']))) {
$has_error = true;
}
else {
$email = trim($_POST['email']);
}
// Check to make sure comments were entered
if(trim($_POST['cf_message']) == '') {
$has_error = true;
}
else {
if(function_exists('stripslashes')) {
$message = stripslashes(trim($_POST['cf_message']));
}
else {
$message = trim($_POST['cf_message']);
}
}
//
// Send E-Mail
//
// Send the email if there is no error
if(!isset($has_error)) {
// Get recheiver
$receiver = ($_POST['cf_receiver']) ? $_POST['cf_receiver'] : get_option('admin_email');
$receiver = str_replace('[at]', '#', $receiver);
// Headers
$headers = "From: $name <$email>\n";
$headers.= "Content-Type: text/plain; charset=\"UTF-8\"\n";
// Message
if($_POST['cf_email_signature'] && $_POST['cf_email_signature'] != 'none') {
$message.= "\n\n---\n".$_POST['cf_email_signature'];
}
// Send E-Mail
$mail_sent = wp_mail($receiver, $subject, $message, $headers);
if($mail_sent)
echo "<p class='info-box success'>".$_POST['cf_success_msg']."</p>";
else
echo "<p class='info-box error'>The message couldn't be sent because an internal error occured.</p>";
echo "<p class='info-box error'>".$_POST['cf_error_msg']."</p>";
}
}
?>
The function for a redirect in wordpress is wp_redirect, e.g.
if( $mail_sent ) {
wp_redirect( '/my-target' );
exit();
} else {
//output your warning
}

PHP Feedback form Checkbox error

Ok here is a shortened version of the php for my contact form, (the checkboxes are not being sent through correctly)
<?php
//please fill this in at least!
$myemail = "";
$title = "Feedback Form";
if(isset($_POST['submit'])) { //form has been submitted
//set variables with filters
$cont_name = filter_var($_POST['cont_name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['cont_email'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['cont_phone'], FILTER_SANITIZE_STRING);
$first_time = filter_var($_POST['first_time'], FILTER_SANITIZE_STRING);
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
function valid_email($str){
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;}
$errors = 0; //by default there are no errors
$trimcont_name = trim($cont_name);
if(empty($trimcont_name)){
//the name field is empty
$errors = 1; //tips off the error messages below
$errorcont_name = "The name field is empty"; //this error is displayed next to the label
}
if(!valid_email($email)) {
//email is invalid or empty
$errors = 1;
$erroremail = "The email address was not valid";
}
$trimphone = trim($phone);
if(empty($trimphone)){
//the phone field is empty
$errors = 1;
$errorphone = "The phone field is empty";
}
$trimfirst_time = trim($first_time);
if(empty($trimfirst_time)){
//the first_time field is empty
$errors = 1;
$errorfirst_time = "This field is empty";
}
$trimhear_about = trim($hear_about);
if(empty($trimhear_about)){
//the hear_about field is empty
$errors = 1;
$errorhear_about = "This field is empty";
}
if($spam != "") {
//spam was filled in
$errors = 1;
$errorspam = "The Spam box was filled in";
}
if($errors == 0) {
$sendto = $myemail;
$message = <<<DATA
DETAILS
Name: $cont_name
Email: $email
Phone: $phone
Was this the first time you have been to us?
$first_time
How did you hear about us?
$hear_about
DATA;
$headers = 'From: ' . $name . '<' . $email . '>';
if(mail($sendto, $title, $message, $headers)) {
//this is where it sends, using the php mail function
$success = true;
//set all the variables to blank to prevent re-submitting.
$cont_name = "";
$email = "";
$phone = "";
$hear_about = "";
$first_time = "";
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
And the area not functioning correctly is
<fieldset>
<legend>How did you hear about us? <span class="phpformerror"><?php echo $errorhear_about; ?></span></legend>
<div><input type="checkbox" name="hear_about[]" value="Web" /> Web</div>
<div><input type="checkbox" name="hear_about[]" value="Newspaper" /> Newspaper</div>
<div><input type="checkbox" name="hear_about[]" value="Radio" /> Radio</div>
<div><input type="checkbox" name="hear_about[]" value="Driving" /> Driving Past</div>
<div><input type="checkbox" name="hear_about[]" value="Referal" /> Referal</div>
<div><input type="checkbox" name="hear_about[]" value="Other" /> Other</div>
</fieldset>
At the moment it will only come through displaying one of the variables if multiple variables are selected.
hear_about is an array and filter_var() does not handle arrays correctly. Instead use filter_var_array():
$hear_about = filter_var_array($_POST['hear_about'], FILTER_SANITIZE_STRING);
Remember that $hear_about is an array, and must be treated like one throughout your code (e.g. just using $hear_about won't work, it needs to be $hear_about[0], $hear_about[1], etc).
So for example in your trim line you would need something like:
foreach($hear_about as $key => $value) {
$trimhear_about[$key] = trim($value);
if(empty($trimhear_about[$key])){
//the hear_about field is empty
$errors = 1;
$errorhear_about[$key] = "This field is empty";
}
}
This will preserve the benefits of dealing with an array.
$_POST['hear_about'] is an array of values. You are handling it as a simple string!
I think you can solve simply replacing the line:
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
With:
$hear_about = filter_var(implode(', ', $_POST['hear_about']), FILTER_SANITIZE_STRING);
The implode function (doc) "transform" an array to a string by concatenating the array values with the given glue. So you can just concatenate selected "How did you hear about us?" options with a comma and then use the resulting string as the other data.

How to validate email address [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to validate an email address in PHP
I was wondering someone can help me please.
I need to validate the email address for the below code but am having problems.
<?php
if ($_POST) {
$expected = array('name', 'email', 'emailmessage');
$validation = array(
'name' => 'Please provide your full name',
'email' => 'Please provide your valid email address',
'emailmessage' => 'Please provide message'
);
$errors = array();
$output = array();
foreach($expected as $key) {
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
if (empty($_POST[$key])) {
$errors[$key] = $validation[$key];
} else {
$output[$key] = $_POST[$key];
}
} else {
$errors[$key] = $validation[$key];
}
}
if (!empty($errors)) {
$array = array('error' => true, 'fields' => $errors);
} else {
// PROCESS FORM
// ---------------------------------------------------------
// BEGIN EDITING
// ---------------------------------------------------------
$to = "qakbar#hotmail.co.uk"; //This is the email address messages will be sent to
$web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox
//get IP address
$ip = $_SERVER['REMOTE_ADDR'];
//make time
$time = time();
$date = date("r", $time);
// ---------------------------------------------------------
// END EDITING
// ---------------------------------------------------------
$emailmessage = trim($emailmessage);
$emailmessage = nl2br($emailmessage);
$emailmessage = htmlspecialchars($emailmessage);
$emailmessage = wordwrap($emailmessage, 70);
//Visible form elements
$name = $_POST['name']; //Sender's name
$email = $_POST['email']; //Sender's email
$emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message
//Setting up email
$subject = "New Message from $web_name";
$message = "
New message from $name <br/><br/>
Message:<br />
$emailmessage
<br/>
<br/>
Email: $email<br />
IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
Date:</strong> $date
";
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$header .= 'From:'. $email . " \r\n";
$sent = mail($to, $subject, $message, $header);
//$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
$array = array('error' => false, 'message' => $message);
}
echo json_encode($array);
}
I want the email to validate in the $validation array as my messages are passed through this and need the email validation to do the same.
I was trying to use the following but did not know where to place it or how to call it.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email is valid
} else {
// email is invalid
}
Any help is much apprecaited.
Thank you
You could use it like this:
filter_var($email, FILTER_VALIDATE_EMAIL) or die("Email wrong.");
Right after you assigned this exact variable:
$email = $_POST['email'];
Of course this could be structured more sensible, and a nicer error notice would also be possible. But it sounds as if you need more general practice with PHP first.
An oddity with your code:
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
You're using the key already BEFORE checking if it exists. As well, the $input variable is not used again in your code, so it's a useless line.
May be, this code will help you. try it.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Categories