Seeking to convert this .php page (that works) with the website input to an email input
I have changed all the websiteField items to emailField including an email Regex but it brings back a error message from the server. 500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.
<?php
require "config.php";
require "connect.php";
if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
$_POST['nameField'] = esc($_POST['nameField']);
$_POST['websiteField'] = esc($_POST['websiteField']);
$_POST['messageField'] = esc($_POST['messageField']);
$error = array();
if(mb_strlen($_POST['nameField'],"utf-8")<2)
{
$error[] = 'Please fill in a valid name.';
}
if(mb_strlen($_POST['messageField'],"utf-8")<2)
{
$error[] = 'Please fill in a longer message.';
}
if(!validateURL($_POST['websiteField']))
{
$error[] = 'The URL you entered is invalid.';
}
$errorString = '';
if(count($error))
{
$errorString = join('<br />',$error);
}
else
{
mysql_query(" INSERT INTO dc_comments (transaction_id, name, url, message)
VALUES (
'".esc($_POST['txn_id'])."',
'".$_POST['nameField']."',
'".$_POST['websiteField']."',
'".$_POST['messageField']."'
)");
if(mysql_affected_rows($link)==1)
{
$messageString = 'You were added to our donor list! »';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thank you!</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body class="thankyouPage">
<div id="main">
<h1>Thank you!</h1>
<h2>Add Yourself to our Donor List. </h2>
<div class="lightSection">
<form action="" method="post">
<div class="field">
<label for="nameField">Name</label>
<input type="text" id="nameField" name="nameField" />
</div>
<div class="field">
<label for="websiteField">Web Site</label>
<input type="text" id="websiteField" name="websiteField" />
</div>
<div class="field">
<label for="messageField">Message</label>
<textarea name="messageField" id="messageField"></textarea>
</div>
<div class="button">
<input type="submit" value="Submit" />
<input type="hidden" name="submitform" value="1" />
<input type="hidden" name="txn_id" value="<?php echo $_POST['txn_id']?>" />
</div>
</form>
<?php
if($errorString)
{
echo '<p class="error">'.$errorString.'</p>';
}
else if($messageString)
{
echo '<p class="success">'.$messageString.'</p>';
}
?>
</div>
</body>
</html>
<?php
function esc($str)
{
global $link;
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(htmlspecialchars(strip_tags($str)),$link);
}
function validateURL($str)
{
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,#?^=%&:\/~\+#]*[\w\-\#?^=%&\/~\+#])?/i',$str);
}
?>
This is the same page with the changes made to reflect email instead of website
<?php
require "config.php";
require "connect.php";
if(isset($_POST['submitform']) && isset($_POST['txn_id']))
{
$_POST['nameField'] = esc($_POST['nameField']);
$_POST['emailField'] = esc($_POST['emailField']);
$_POST['messageField'] = esc($_POST['messageField']);
$error = array();
if(mb_strlen($_POST['nameField'],"utf-8")<2)
{
$error[] = 'Please fill in a valid name.';
}
if(mb_strlen($_POST['messageField'],"utf-8")<2)
{
$error[] = 'Please fill in a longer message.';
}
if(!validate_email($_POST['emailField']))
{
$error[] = 'The email you entered may be invalid! Please check same.';
}
$errorString = '';
if(count($error))
{
$errorString = join('<br />',$error);
}
else
{
mysql_query(" INSERT INTO dc_comments (transaction_id, name, email, message)
VALUES (
'".esc($_POST['txn_id'])."',
'".$_POST['nameField']."',
'".$_POST['emailField']."',
'".$_POST['messageField']."'
)");
if(mysql_affected_rows($link)==1)
{
$messageString = 'You were added to our donor list! »';
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Thank you!</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body class="thankyouPage">
<div id="main">
<h1>Thank you for your support!</h1>
<h2>Add your name to the donor list. </h2>
<div class="lightSection">
<form action="" method="post">
<div class="field">
<label for="nameField">Name</label>
<input type="text" id="nameField" name="nameField" />
</div>
<div class="field">
<label for="emailField">Email</label>
<input type="text" id="emailField" name="emailField" />
</div>
<div class="field">
<label for="messageField">Message</label>
<textarea name="messageField" id="messageField"></textarea>
</div>
<div class="button">
<input type="submit" value="Submit" />
<input type="hidden" name="submitform" value="1" />
<input type="hidden" name="txn_id" value="<?php echo $_POST['txn_id']?>" />
</div>
</form>
<?php
if($errorString)
{
echo '<p class="error">'.$errorString.'</p>';
}
else if($messageString)
{
echo '<p class="success">'.$messageString.'</p>';
}
?>
</div>
</body>
</html>
<?php
function esc($str)
{
global $link;
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
return mysql_real_escape_string(htmlspecialchars(strip_tags($str)),$link);
}
function validate_email($str)
{
return preg_match('.*?#.*?\...*', $str);
}
?>
Why will the email not work as planned and is the approach correct?
I am working with this DonationScript
Your problem may be in your regexp, the * is an unknown modifier in your code example. Try this... Delete the validate email function completely. Then change
if(!validate_email($_POST['emailField']))
to
if (!filter_var($_POST['emailField'], FILTER_VALIDATE_EMAIL))
and see if that works for you.
Related
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 :
I am trying to write a basic blog that i can post blogs and view them blogs. I have posted the blog by form action however what i want to try to do now is that get the data that i got from my csv into h1 h2 p2 on my viewpost.html. How would i be able to do this.
This is my index.html
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
<link type='text/css' rel ='stylesheet' href="style.css"/>
</head>
<body>
<form action="form_process.php" method="post">
<label for="title">Title</label>
<input type="text" name="title" id='title'/>
<label for="desc">Description</label>
<input type="text" name="desc" id='desc'/>
<label for="cont">Content</label>
<input type="text" name="cont" id='cont'/>
<input type="submit" name="formSubmit" value="Submit" />
</body>
</html>
This is form_process.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['title']))
{
$errorMessage .= "<li>You forgot to enter a title!</li>";
}
if(empty($_POST['desc']))
{
$errorMessage .= "<li>You forgot to enter a description!</li>";
}
if(empty($_POST['cont']))
{
$errorMessage .= "<li>You forgot to enter a description!</li>";
}
$varTitle = $_POST['title'];
$varDesc = $_POST['desc'];
$varCont = $_POST['cont'];
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varTitle . ", " .$varDesc . ", " .$varCont . "\n");
fclose($fs);
header("Location: index.html");
exit;
}
}
?>
And lastly this is my viewpost.html
<!DOCTYPE html>
<html>
<head>
<title> View Post</title>
</head>
<body>
<div class="post">
<h1>Title</h1>
<h2>Description</h2>
<p>Content</p>
</body>
</html>
Okay, so after I read your initial post i did an UPDATE to the code (in an attempt to make it read simpler) per my understanding because, again, i'm a newbie to this. And looking back now, that may be the problem. So I appreciate you patience; please don't kill me ... Here's what I changed it to and tested on the server:
Here's the actual webpage (ContactsUs.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="PSStyles.css" rel="stylesheet" type="text/css">
<title>Contact Us Form</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#qForm").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
comments: "required"
},
messages: {
firstname: "First Name Required",
lastname: "Last Name Required",
email: {
required: "Email Required",
email: "Invalid Email Address"
},
comments: "You must write a message"
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<?php include 'header1.php'?>
</div>
<div id="ripmain">
<div id="menuet">
<nav>
<ul id="menubar">
<li>Home</li>
<li>About</li>
<li>Location</li>
<li>Grooming</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
</div>
<form method="POST" action="contact.php" id="qForm">
<fieldset width="954px">
<legend>Contact Us Form</legend>
<p>First Name: <input type="text" size="32" name="firstname" /></p>
<p>Last Name: <input type="text" size="32" name="lastname" /></p>
<p>Email: <input type="text" size="32" id="email" name="email" /></p>
<div id="rsp_email"><!-- --></div>
<td>Comments: </td>
<td>
<textarea name="Comments" cols="40" rows="3" wrap="virtual"></textarea>
</td>
<input type="hidden" name="subject" value="online_submission" />
<p><input type="submit" value="submit"></p>
</fieldset>
</form>
<?php include 'footer1.php';?>
</div>
</body>
</html>
Then I changed the action file (contact.php) to:
<?php
if(isset($_POST['firstname'])) {
$contact = validate_inputs($_POST);
if(in_array(false, $contact) === true) {
echo process_errors($contact);
exit;
}
else {
/* Let's prepare the message for the e-mail */
ob_start();
?>Hello!
Your contact form has been submitted by:
First Name: <?php echo $contact['firstname']; ?>
Last Name: <?php echo $contact['lastname']; ?>
E-mail: <?php echo $contact['email']; ?>
Comments:
<?php echo $contact['comments']; ?>
End of message
<?php
$message = ob_get_contents();
ob_end_clean();
// Send the message here
if(send_email(array("to"=>"greatscott971#gmail.com","from"=>$contact['email'],"subject"=>$contact['subject'],"message"=>$contact['comments']))) {
header('Location: thanks.html');
exit();
}
else
die("An error occurred while sending. Please contact the administrator.");
}
}
?>
So, THIS MORNING i've gone back and applied the actual changes as you suggested. The problem is that i'm getting a syntax error on line 140 in the php tag after the closing html tag. it has a problem with one of the closing brackets. Here's this code which would be the new webpage (ContactForm.php):
function error_codes($code = false)
{
$valid['firstname'] = "Enter your name";
$valid['lastname'] = "Enter your name";
$valid['subject'] = "Write a subject";
$valid['email'] = "Invalid email";
$valid['comments'] = "Write your comments";
return (isset($valid[$code]))? $valid[$code] : false;
}
// Run the validation and return populated array
function validate_inputs($REQUEST)
{
/* Check all form inputs using check_input function */
$valid['firstname'] = check_input($REQUEST['firstname']);
$valid['lastname'] = check_input($REQUEST['lastname']);
$valid['subject'] = check_input($REQUEST['subject']);
$valid['email'] = check_input($REQUEST['email'],"email");
$valid['comments'] = check_input($REQUEST['comments']);
return $valid;
}
// Modify your validate function a bit to do only validation, no returning of errors
function check_input($data = false, $type = false)
{
if($type == 'email')
return (filter_var($data,FILTER_VALIDATE_EMAIL))? $data : false;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return (!empty($data))? $data : false;
}
// This will loop through returned values and populate errors based on empty
function process_errors($array = false)
{
if(!is_array($array))
return $array;
foreach($array as $key => $value) {
if(empty($value))
$errors[] = error_codes($key);
}
return (!empty($errors))? show_error($errors) : false;
}
// display errors via buffer output
function show_error($myError)
{
ob_start();
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/css/default.css" rel="stylesheet">
<title>Contact Us Form</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#qForm").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
comments: "required"
},
messages: {
firstname: "First Name Required",
lastname: "Last Name Required",
email: {
required: "Email Required",
email: "Invalid Email Address"
},
comments: "You must write a message"
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
<h1 id="sitename"><img src="Images/logo.jpg" alt="logo" width="270" height="105" /></span></h1>
<h2 class="description">The home for pampered pets.</h2>
</div>
<div id="headercontent">
<h2>Happy Pets-timonials</h2>
<p>My owner took me to Sandy's for a bath and I got the 'spaw' treatment. - Rover</p>
</div>
<div id="sitecaption"> Satisfaction <span class="bigger">Guaranteed</span> </div>
</div>
<div id="ripmain">
<div id="menuet">
<nav>
<ul id="menubar">
<li>Home</li>
<li>About</li>
<li>Location</li>
<li>Grooming</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
<form method="POST" action="ContactProcess.php" id="qForm">
<fieldset>
<legend>Contact Us Form</legend>
<p>First Name: <input type="text" size="32" name="firstname" /></p>
<p>Last Name: <input type="text" size="32" name="lastname" /></p>
<p>Email: <input type="text" size="32" id="email" name="email" /></p>
<div id="rsp_email"><!-- --></div>
<td>Comments: </td>
<td>
<textarea name="comments" cols="40" rows="3" wrap="virtual"></textarea>
</td>
<input type="hidden" name="subject" value="online_submission" />
<p><input type="submit" value="Submit"></p>
</fieldset>
</form>
<div id="footer"> © Copyright 2015 Time Live, Inc. All rights reserved. <br>
Hours: Mon-Fri: 6 am to 11 pm; Sat & Sun: 8 am to 10pm <br>
Links to other local services: <li>Hillside Vet Clinic</li> <li>PetSmart Stores</li> <li>Pooch Hotel </div>
</body>
</html>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function send_email($settings = false)
{
$to = (!empty($settings['to']))? $settings['to']:false;
$from = (!empty($settings['from']))? "From:".$settings['from'].PHP_EOL:false;
$subject = (!empty($settings['subject']))? $settings['subject']:false;
$message = (!empty($settings['message']))? $settings['message']:false;
if(in_array(false, $settings) === true)
return false;
return (mail($to,$subject,$message));
}
?>
And here's the new post file (ContactProcess.php) per your suggestion:
<?php
if(isset($_POST['firstname'])) {
$contact = validate_inputs($_POST);
if(in_array(false, $contact) === true) {
echo process_errors($contact);
exit;
}
else {
/* Let's prepare the message for the e-mail */
ob_start();
?>Hello!
Your contact form has been submitted by:
First Name: <?php echo $contact['firstname']; ?>
Last Name: <?php echo $contact['lastname']; ?>
E-mail: <?php echo $contact['email']; ?>
Comments:
<?php echo $contact['comments']; ?>
End of message
<?php
$message = ob_get_contents();
ob_end_clean();
// Send the message here
if(send_email(array("to"=>"greatscott971#gmail.com","from"=>$contact['email'],"subject"=>$contact['subject'],"message"=>$contact['comments']))) {
header('Location: thanks.html');
exit();
}
else
die("An error occurred while sending. Please contact the administrator.");
}
}
I have not tested this second code; but will do so and let you know what i find; in the meantime any advice on the revised/updated code above? Thanks again for your help ...
Try splitting up some of your logic into little functions, it is easier to keep track of tasks. Also for the form, try using form validation via jQuery:
form page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/css/default.css" rel="stylesheet">
<title>Contact Us Form</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#qForm").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
comments: "required"
},
messages: {
firstname: "First Name Required",
lastname: "Last Name Required",
email: {
required: "Email Required",
email: "Invalid Email Address"
},
comments: "You must write a message"
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="logo">
<h1 id="sitename"><img src="Images/logo.jpg" alt="logo" width="270" height="105" /></span></h1>
<h2 class="description">The home for pampered pets.</h2>
</div>
<div id="headercontent">
<h2>Happy Pets-timonials</h2>
<p>My owner took me to Sandy's for a bath and I got the 'spaw' treatment. - Rover</p>
</div>
<div id="sitecaption"> Satisfaction <span class="bigger">Guaranteed</span> </div>
</div>
<div id="ripmain">
<div id="menuet">
<nav>
<ul id="menubar">
<li>Home</li>
<li>About</li>
<li>Location</li>
<li>Grooming</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
<form method="POST" action="contact.php" id="qForm">
<fieldset>
<legend>Contact Us Form</legend>
<p>First Name: <input type="text" size="32" name="firstname" /></p>
<p>Last Name: <input type="text" size="32" name="lastname" /></p>
<p>Email: <input type="text" size="32" id="email" name="email" /></p>
<div id="rsp_email"><!-- --></div>
<td>Comments: </td>
<td>
<textarea name="comments" cols="40" rows="3" wrap="virtual"></textarea>
</td>
<input type="hidden" name="subject" value="online_submission" />
<p><input type="submit" value="Submit"></p>
</fieldset>
</form>
<div id="footer"> © Copyright 2015 Time Live, Inc. All rights reserved. <br>
Hours: Mon-Fri: 6 am to 11 pm; Sat & Sun: 8 am to 10pm <br>
Links to other local services: <li>Hillside Vet Clinic</li> <li>PetSmart Stores</li> <li>Pooch Hotel </div>
</body>
</html>
functions required on the contact form:
// This will return error messages (you could expand it to be database driven)
function error_codes($code = false)
{
$valid['firstname'] = "Enter your name";
$valid['lastname'] = "Enter your name";
$valid['subject'] = "Write a subject";
$valid['email'] = "Invalid email";
$valid['comments'] = "Write your comments";
return (isset($valid[$code]))? $valid[$code] : false;
}
// Run the validation and return populated array
function validate_inputs($REQUEST)
{
/* Check all form inputs using check_input function */
$valid['firstname'] = check_input($REQUEST['firstname']);
$valid['lastname'] = check_input($REQUEST['lastname']);
$valid['subject'] = check_input($REQUEST['subject']);
$valid['email'] = check_input($REQUEST['email'],"email");
$valid['comments'] = check_input($REQUEST['comments']);
return $valid;
}
// Modify your validate function a bit to do only validation, no returning of errors
function check_input($data = false, $type = false)
{
if($type == 'email')
return (filter_var($data,FILTER_VALIDATE_EMAIL))? $data : false;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return (!empty($data))? $data : false;
}
// This will loop through returned values and populate errors based on empty
function process_errors($array = false)
{
if(!is_array($array))
return $array;
foreach($array as $key => $value) {
if(empty($value))
$errors[] = error_codes($key);
}
return (!empty($errors))? show_error($errors) : false;
}
// display errors via buffer output
function show_error($myError)
{
ob_start();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<b>Please correct the following error:</b><br />
<?php echo implode("<br />".PHP_EOL,$myError); ?>
</body>
</html>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function send_email($settings = false)
{
$to = (!empty($settings['to']))? $settings['to']:false;
$from = (!empty($settings['from']))? "From:".$settings['from'].PHP_EOL:false;
$subject = (!empty($settings['subject']))? $settings['subject']:false;
$message = (!empty($settings['message']))? $settings['message']:false;
if(in_array(false, $settings) === true)
return false;
return (mail($to,$subject,$message));
}
contact.php:
// Include above functions
if(isset($_POST['firstname'])) {
$contact = validate_inputs($_POST);
if(in_array(false, $contact) === true) {
echo process_errors($contact);
exit;
}
else {
/* Let's prepare the message for the e-mail */
ob_start();
?>Hello!
Your contact form has been submitted by:
First Name: <?php echo $contact['firstname']; ?>
Last Name: <?php echo $contact['lastname']; ?>
E-mail: <?php echo $contact['email']; ?>
Comments:
<?php echo $contact['comments']; ?>
End of message
<?php
$message = ob_get_contents();
ob_end_clean();
// Send the message here
if(send_email(array("to"=>"greatscott971#gmail.com","from"=>$contact['email'],"subject"=>$contact['subject'],"message"=>$contact['comments']))) {
header('Location: thanks.html');
exit();
}
else
die("An error occurred while sending. Please contact the administrator.");
}
}
I'm unable to solve the logical error in the code. I'm not sure what is wrong though it seems the logic is correct
This is my php:
<?php require_once("includes/connection.php"); ?>
<?php
include_once("includes/form_functions.php");
if(isset($_POST['submit']))
{
$errors = array();
if(isset($_POST['txtSpace']))
{
$choice_spc_port = $_POST["txtSpace"];
}
if(isset($_POST['txtNumber']))
{
$choice_no = $_POST["txtNumber"];
}
if(isset($_POST['txtLocation']))
{
$choice_loc = $_POST["txtLocation"];
if($choice_loc =="txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
if($x == "")
{
$message = "You forgot to enter X Value";
}
elseif($y == "")
{
$message = "You forgot to enter Y Value";
}
else
{
$choice_loc = $x . "," . $y;
}
}
}
$user_name = $_POST["txtUserName"];
$user_email = $_POST["txtUserEMail"];
$animal_name = $_POST["txtAnimalName"];
$disp_msg = $_POST["txtDispMsg"];
$comments = $_POST["txtComments"];
if(!isset($_POST['txtSpace']))
{
$message = "Please select Space Portion";
}
elseif(!isset($_POST['txtNumber']))
{
$message = "Please select the number of animals";
}
elseif(!isset($_POST['txtLocation']))
{
$message = "Please select the desired location of animal";
}
elseif($user_name == "")
{
$message = "Please enter your name.";
}
elseif($user_email == "")
{
$message = "Please enter your email.";
}
elseif($animal_name == "")
{
$message = "Please enter the name of the animal.";
}
elseif($disp_msg == "")
{
$message = "What message you want to dedicate to the animal?.";
}
else
{
// validation
$required_fields = array('txtUserName','txtUserEMail','txtAnimalName','txtDispMsg');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$user_name = trim(mysql_prep($_POST['txtUserName']));
$user_email = trim(mysql_prep($_POST['txtUserEMail']));
$animal_name = trim(mysql_prep($_POST['txtAnimalName']));
$disp_msg = trim(mysql_prep($_POST['txtDispMsg']));
if(empty($errors))
{
/*if($choice_loc == "txtSetXY")
{
$x = $_POST["txtXLocation"];
$y = $_POST["txtYLocation"];
$choice_loc = $x . "," . $y;
}*/
if($choice_no == "other")
{
$choice_no = $_POST["other_field"];
}
$insert = "INSERT INTO db_form (db_space_portion, db_number, db_location, db_user_name, db_user_email, db_animal_name, db_message, db_comments) VALUES ('{$choice_spc_port}', '{$choice_no}', '{$choice_loc}', '{$user_name}', '{$user_email}','{$animal_name}','{$disp_msg}','{$comments}')";
$result = mysql_query($insert);
if($result)
{
echo("<br>Input data is succeed");
}
else
{
$message = "The data cannot be inserted.";
$message .= "<br />" . mysql_error();
}
}
else
{
if(count($errors) == 1)
{
$message = "There was 1 error on the form.";
}
else
{
$message = "There were " . count($errors) ." errors on the form.";
}
}
}
}
else
{
$user_name = "";
$user_email = "";
$disp_msg = "";
$comments = "";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/reset.css" type="text/css" media="all">
<link rel="stylesheet" href="css/layout.css" type="text/css" media="all">
<link rel="stylesheet" href="css/style.css" type="text/css" media="all">
<script type="text/javascript" src="js/jquery-1.9.0.min.js" ></script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/cufon-replace.js"></script>
<script type="text/javascript" src="js/Copse_400.font.js"></script>
<script type="text/javascript" src="js/imagepreloader.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<!--[if lt IE 9]>
<script type="text/javascript" src="js/ie6_script_other.js"></script>
<script type="text/javascript" src="js/html5.js"></script>
<![endif]-->
</head>
<body id="page5">
<!-- START PAGE SOURCE -->
<div class="body7">
<div class="main">
<section id="content">
<div class="wrapper">
<article class="col24">
<div class="pad1">
<h4>Kindly Fill the form</h4>
<?php if(!empty($message)){ echo $message; } ?>
<?php if(!empty($errors)){ echo display_errors($errors);}?>
<form id="TestForm" name="TestForm" method="post" action="form.php">
<div>
<div class="wrapper"> <strong><span>*</span> Desired Space</strong>
<div class="formText">
<input type="radio" name="txtSpace" value="RJ"/>Space Top<br />
<input type="radio" name="txtSpace" value="SM" />Space Bottom<br />
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select the Number</strong>
<div class="formText">
<input type="radio" name="txtNumber" value="100"/>100
<input type="radio" name="txtNumber" value="200"/>200
<input type="radio" name="txtNumber" value="500"/>500
<input type="radio" name="txtNumber" value="1000"/>1000
<input type="radio" name="txtNumber" value="10000"/>10000
<input type="radio" name="txtNumber" value="other"/>other
<input type="text" name="other_field" id="other_field" onblur="checktext(this);"/>
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Select X & Y Value</strong>
<div class="formText">
<input type="radio" name="txtLocation" value="txtSetXY"/> Specify Photo Location<br />
<div style="padding-left:20px;">
X: <input type="text" id="locField" name="txtXLocation"><br />
Y: <input type="text" id="locField" name="txtYLocation"><br />
</div>
<input type="radio" name="txtLocation" value="Default"/>Default
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Name:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserName">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Your Email:</strong>
<div class="bg">
<input type="text" class="input" name="txtUserEMail">
</div>
</div>
<div class="wrapper"> <strong><span>*</span> Name of the animal:</strong>
<div class="bg">
<input type="text" class="input" name="txtAnimalName">
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong><span>*</span> The Message you want for your favourite animal:</strong>
<textarea name="txtDispMsg" cols="1" rows="1"></textarea>
</div>
</div>
<div class="wrapper">
<div class="textarea_box"> <strong>Comments:</strong>
<textarea name="txtComments" cols="1" rows="1"></textarea>
</div>
</div>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</div>
</article>
</div>
</section>
</div>
</div>
</body>
</html>
Errors:
Check this php fiddle here.
line 25. This is never shown even if I leave x textfield blank
$message = "You forgot to enter X Value";
same is with line 29. This is never shown even if I leave y textfield blank
$message = "You forgot to enter Y Value";
However if I enter the values in x and y textfield i.e. in txtXLocation and in txtYLocation they are being saved in db meaning it is just not checking the validation.
Thanks in advance
make sure you have connection.php file in includes folder and you have given correct path to reach that file.
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.