Contact Form textarea deleting on Submission - php

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

Related

How do I input/output .CSV data via a PHP page?

I have the assignment below and I'm stuck at Step # 3 with the code file named inputforassignment2.php --basically, I am trying to append (add) rows to the existing data (songs.csv file) via that file with input fields. I tried to fix that code (which i obtained from a website, see sample source code far below, but it's returning errors or creates blank and numerical data in rows for each input.
Assignment: Create a simple PHP page that reads/writes to and from a .CSV file
The .CSV file should contain a list of your favorite items (for
example: songs, games, books, authors, etc,..). Each record in your
file should contain at least 3 attributes for your favorite item.
Also, it should have at least 7 records. --this part is done
The PHP should read the file and display the records in a TABLE with
the corresponding headers for each attribute of your favorite item.
--this part is done
Also, in the page should be a link (<< I did that part) that takes to another page where a new record can be added to the file. Then the list should display all previous records plus the new one. (<< where I am stuck)
-all my current source files:
song.csv
Song Title,Artist,Track Year
FLY,Sik-K,2017
Doverstreet,RIN,2017
Half Moon,Dean,2016
Blacklist,Loopy,2017
N/A,JooYoung,2018
Heyahe,ONE,2017
ADY,Sik-K,2017
assignment2.php how this php code displays song.csv
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 2</title>
</head>
<?php
echo "<table border=1> ";
$f = fopen("song.csv", "r"); //open a file in read mode
while (($line = fgetcsv($f)) !== false) { //read the each line of csv file
echo "<tr>"; //for printing in the table
foreach ($line as $cell) { //each data of line
echo "<td>" . htmlspecialchars($cell) . "</td>"; //print in the table
}
echo "</tr> ";
}
fclose($f); //close file
echo " </table>";
?>
Click here to add more songs!
<body>
</body>
</html>
inputformassignment2.php
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add A New Song</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">Add A New Song</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Type below:</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Song Title</label>
<input type="text" name="name" placeholder="Type your song title" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Song Artist</label>
<input type="text" name="email" class="form-control" placeholder="Type the song artist here" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Track Year</label>
<input type="text" name="subject" class="form-control" placeholder="Put the song's track year here" value="<?php echo $subject; ?>" />
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
sample source code obtained from website:
<?php
//index.php
$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';
function clean_text($string)
{
$string = trim($string);
$string = stripslashes($string);
$string = htmlspecialchars($string);
return $string;
}
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
}
else
{
$name = clean_text($_POST["name"]);
if(!preg_match("/^[a-zA-Z ]*$/",$name))
{
$error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
}
}
if(empty($_POST["email"]))
{
$error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
}
else
{
$email = clean_text($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= '<p><label class="text-danger">Invalid email format</label></p>';
}
}
if(empty($_POST["subject"]))
{
$error .= '<p><label class="text-danger">Subject is required</label></p>';
}
else
{
$subject = clean_text($_POST["subject"]);
}
if(empty($_POST["message"]))
{
$error .= '<p><label class="text-danger">Message is required</label></p>';
}
else
{
$message = clean_text($_POST["message"]);
}
if($error == '')
{
$file_open = fopen("contact_data.csv", "a");
$no_rows = count(file("contact_data.csv"));
if($no_rows > 1)
{
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'sr_no' => $no_rows,
'name' => $name,
'email' => $email,
'subject' => $subject,
'message' => $message
);
fputcsv($file_open, $form_data);
$error = '<label class="text-success">Thank you for contacting us</label>';
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>How to Store Form data in CSV File using PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">How to Store Form data in CSV File using PHP</h2>
<br />
<div class="col-md-6" style="margin:0 auto; float:none;">
<form method="post">
<h3 align="center">Contact Form</h3>
<br />
<?php echo $error; ?>
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
</div>
<div class="form-group">
<label>Enter Email</label>
<input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
</div>
<div class="form-group">
<label>Enter Subject</label>
<input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
</div>
<div class="form-group">
<label>Enter Message</label>
<textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>

Simple php command not working?

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>'
}
?>

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?

Form $_SESSION data Issue

I have designed a form which check validation when it is sent, I am using Swiftmailer and all of the validation works however I have a problem. When I return back to the contact form the errors are still there if they filled it out wrong so...
name is required!
email is required!
the errors only go when it passes validation.
How do I refresh the page when the user leaves and comes back to a fresh form?
Contact form:
<?php
session_start();
?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Send a message</title>
</head>
<body>
<div class="container">
<div <?php if(isset($_SESSION['form_message'])) { echo 'style="color: green"'; } elseif (isset($_SESSION['form_errors'])) { echo 'style="color: red"'; } ?>>
<?php
if(isset($_SESSION['form_message']))
{
echo $_SESSION['form_message'];
unset($_SESSION['form_data']);
}
elseif(isset($_SESSION['form_errors']))
{
echo '<b>You have the following errors:</b>';
echo "<br>";
foreach($_SESSION['form_errors'] as $display_err) {
echo $display_err . "<br>";
}
}
?>
</div>
<form name="contact" method="post" action="swift_mail.php">
<div>
<label for="name">Full name</label><br />
<input type="text" name="name" id="name" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['name'] ; } ?>" />
</div>
<div>
<label for="email">Email Address</label><br />
<input type="text" name="email" id="email" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['email'] ; } ?>" />
</div>
<div>
<label for="comment">Comment</label><br />
<textarea name="comment" id="comment"><?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['comment'] ; } ?></textarea>
<input type="submit" value="submit" name="submit_msg"/>
</div>
</form>
</div>
</body>
</html>
</code>
swift
<?php
session_start();
require_once 'Swift-5.0.3/lib/swift_required.php';
require 'vendor/autoload.php';
if(isset($_POST['submit_msg'])) {
/*
Validate data before it is posted
*/
$rule_set = array (
'name' => array(
'required'
),
'email' => array(
'required'
),
'comment' => array(
'required'
)
);
/*
Checking Validation
*/
$validation_result = SimpleValidator\Validator::validate($_POST, $rule_set);
if ($validation_result->isSuccess() == true ) {
/*
Contact Form Information
*/
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Main Point of contact
$email_address = 'ben#bubbledesign.co.uk';
// Composed Message
$body_msg = "Name: " . $name . "<br>" . "Comments: " .$comment;
/*
Swift Mail Transport
*/
$transport = Swift_MailTransport::newInstance();
$mail = Swift_Mailer::newInstance($transport);
/*
Create the Swift Message
*/
$message = Swift_Message::newInstance('Subject line')
->setFrom($email)
->setTo($email_address)
->setBody($body_msg, "text/html");
/*
Send Swift Message
*/
$result = $mail->send($message);
$_SESSION['form_message'] = "Thank you for your message someone will be in touch soon.";
unset($_SESSION['form_errors']);
unset($_SESSION['form_data']);
header('location: contact-form.php');
} else {
$_SESSION['form_data'] = $_POST;
$_SESSION['form_errors'] = $validation_result->getErrors();
header('Location: contact-form.php');
}
}
?>

SESSION variable value is not passing

I'm trying to pass a value from a select input control on an HTML form.
When I hardcode it, it gets echoed, when not, all I get is this:
The invention type did not go through correctly.
Here is my page1.php:
<?php
session_start();
$_SESSION['invtype'] = $invtype;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if (!$errors) {header("location: offerform_switch.php");
}
else {
echo '<div style="color: red">' . $errors . '<br/>
</div>';
}
}
?>
<!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" lang="en" xml:lang="en">
<head>
<title>Offer Form, Part 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="inventron_sage_short.css" type="text/css" />
<link rel="stylesheet" href="form.css" type="text/css" />
</head>
<body>
<div id = "logo">
<img src = "img/top.jpg" alt = "logo" />
</div>
<div id = "wrapper">
<div id="stylized" class="myform">
<form id="form" action="page1.php" method="post">
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<div id = "category">Categorize your invention:</div>
<div class="spacer"></div>
<p>
<select id="invtype" name="invtype">
<option value="0" selected="selected">Select type</option>
<option value="product">PRODUCT</option>
<option value="software">SOFTWARE</option>
</select>
<input type="submit" name="Submit" value="Next!" />
</div>
</div>
</body>
</html>
Here is my offerform_switch.php:
<?php
session_start();
// echo variable from the session, we set this on our other page
echo $_SESSION['invtype'];
$invtype = $_SESSION['invtype'];
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("mysql.myserver.com","myuser","mypassword"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("invention") or die("Unable to select database"); //select which database we're using
switch ($invtype){
case "product":
include("page2_product.php");
break;
case "software":
include("page2_software.php");
break;
default:
echo "The invention type did not go through correctly.";
}
?>
What am I doing wrong?
Thank you!
It should be
$_SESSION['invtype'] = $_POST['invtype'];
You're missing "session_id();" right below the "session_start();". I don't know why exactly it's required, but if I remember correctly, it is.

Categories