Checkbox value not displaying - php

The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>

If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.

The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];

If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.

Give action in your form in contact.php
<form action="form.php">

Related

Look up MX server and display

I'm trying to make a script that receives "email" in GET and then displays MX server and i tired this code it did not work!
<?php
$email = $_GET['email'];
list($username,$domain) = split("#",$email);
echo getmxrr($domain)
?>
Found the answer
<?php
//$email = $_GET['email'];
//list($username,$domain) = split("#",$email);
//echo getmxrr($domain)
$email = $_GET['email'];
list($username,$domain) = split("#",$email);
$mxlist = array();
echo getmxrr($domain,$mxlist);
foreach($mxlist as $value){
echo $value . "<br>";
}
?>

Passing on validated variables to a different page (PHP)

On form index.php I have three input fields (Name, Surname and Date of Birth) which I want to pass along to form myProfile.php, the user cannot continue to the next myProfile.php unless all three fields have been completed.
How can I send the variables to the next page, once it has been determined that all the input fields are valid? Currently I can determine that all the input fields are valid, but I don't know how to pass the variables along to myProfile.php
Variables and Input handling (index.php):
<?php
$nameErr = $surnameErr = $dobErr = "";
$name = $surname = $dob = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
}
if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = test_input($_POST["dob"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Creating the form (index.php):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Surname:
<input type="text" name="surname">
<span class="error">* <?php echo $surnameErr;?></span>
<br><br>
Date of Birth:
<input type="date" name="dob">
<span class="error">*<?php echo $dobErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
My problem is that in order to send my name, surname and date of birth to myProfile.php, I need the form action to be action="myProfile.php", however for the input validation to take place it has to be action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>". How can I allow the input validation to take place, and if all the input is valid, then pass the variables along to myProfile.php in order to use the following code:
myProfile.php:
<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";
?>
You should be able to use PHP's session functionality to do this. Sessions are not specific to PHP, but PHP has functions which make it easy to maintain data about a specific visitor. This can be tricky because HTTP is a stateless protocol.
In index.php, after you have made sure that the data is valid you can store it in session by calling session_start and using the superglobal $_SESSION variable:
if ($data_is_valid) // you'll have to figure out yourself whether data is valid or not
{
session_start(); // you must call this before using $_SESSION
$_SESSION["valid_data"] = array(
"name" => $name,
"surname" => $surname,
"dob" => $dob
);
// redirect the user to the other page
header("location: myProfile.php");
// always remember to exit after redirecting or code may continue to execute
exit;
}
Then, in my Profile.php, you can call session_start and check for the valid data
session_start();
if (!array_key_exists("valid_data", $_SESSION)) {
die("No valid data found!"); // you might want to redirect back to the first page or something?
}
$data = $_SESSION["valid_data"];
if (!is_array($data)) {
die("Data found is not an array!");
}
// otherwise, data was found...you can keep going!
// you might get errors here if you didn't set these properly on the the previous page
$name = $data['name'];
$surname = $data['surname'];
$dob = $data['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";

Submit PHP form to different addresses dependant on option selected from dropdown

How can I submit a form to one of 4 different addresses depending on what the user selects from a dropdown?
So 4 options are 1,2,3,4 (in my case these are different branches) If 1 is selected I want the form to submit to 1#email.com, if 2 is selected the form should go to 2#email.com etc.
I saw similar questions on here but always seem to be database or wordpress related.
The processor for the form looks like this:
<?php
include_once "includes/funcs.php";
$success=$_GET['success'];
if(isset($_POST['submit']))
{
/* Check all form inputs using check_input function */
$name = trim(stripslashes(htmlspecialchars($_POST['InputName'])));
$email = trim(stripslashes(htmlspecialchars($_POST['InputEmail'])));
$phone = trim(stripslashes(htmlspecialchars($_POST['InputPhone'])));
$branch = trim(stripslashes(htmlspecialchars($_POST['InputBranch'])));
$message = trim(stripslashes(htmlspecialchars($_POST['InputMessage'])));
$j=0;
$filecount=count($_FILES['upload']['name']);
for($i=0; $i<$filecount; $i++)
{
//Get the temp file path
//Make sure we have a filepath
if ($_FILES['upload']['size'][$i]<=2048000){
$filep[$j]=$_FILES['upload']['tmp_name'][$i];
$filen[$j]=$_FILES['upload']['name'][$i];
$j+=1;
//echo $files[$i]."<br/><br/>";
}
}
$subject = "You have received an enquiry";
$message = "
This is a message via the website:
Name: $name
Email: $email
Subject: $subject
Telephone: $phone
Branch: $branch
Message:
$message
";
//echo "here";
/* Send the message using mail() function */
emailPerson($subject,$message,'xx#emailaddress.com',$filep,$filen);
/* Redirect visitor to the thank you page */
$success=1;
$name = "";
$email = "";
$phone = "";
$branch = "";
$message = "";
header('Location: thanks-for-your-interest.php');
//exit();
}
include_once "includes/top.php";
?>
and the HTML:
<label for="InputBranch">Please select the branch you wish to send this message to:</label>
<div class="input-group">
<select class="form-control" name='InputBranch' id='InputBranch' required >
<option value="Branch 1">1</option>
<option value="Branch 2">2</option>
<option value="Branch 3">3</option>
<option value="Branch 4">4</option>
</select>
<span class="input-group-addon"><i class="glyphicon glyphicon-ok form-control-feedback"></i></span></div>
</div>
Currently the logic tells it to submit to xx#emailaddress.com each time and just picks up the name of the branch in the email but I need it to go to the relevant branch.
Thanks
Simple: just check what the value POSTed was for your input. In your case, it’s called InputBranch:
switch ($_POST['InputBranch']) {
case 'Blackpool':
$email = 'blackpool#exmaple.com';
break;
case 'Kendal':
$email = 'kendal#exmaple.com';
break;
case 'Lancaster':
$email = 'lancaster#exmaple.com';
break;
case 'Preston':
$email = 'preston#exmaple.com';
break;
default:
throw new Exception('Invalid branch selected.')
}
mail($email, $subject, $message, $headers);
Also, you don’t need to reset variables here:
$success=1;
$name = "";
$email = "";
$phone = "";
$branch = "";
$message = "";
header('Location: thanks-for-your-interest.php');
If you’re just going to redirect. The variables’ values won’t persist between pages.
You could do:
<?php
$recipients = array(
'Branch 1' => 'email1#domain.com',
'Branch 2' => 'email2#domain.com',
'Branch 3' => 'email3#domain.com',
'Branch 4' => 'email4#domain.com',
);
if (isset($recipients[$branch])) {
$to = $recipients[$branch];
} else {
// invalid branch selected
}
You could put this after you assign the variables from $_POST and it will select the recipient from the array based on the submitted form value.

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