UPDATED specific to this code on emailer submit button - php

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.");
}
}

Related

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

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

localhost mail php code showing on page

I'm having some code show up on my mail php block. It has happened with every form tutorial I've gone through. Well, it works with the basic form, but when I try a form that adds a bit of security, I get code showing through.
I'm using a css template provided online as well as a php mail code found online as well. When I pull up the stand alone code in XAMPP it looks fine, but when I incorporate it into my html, the code bleeds through.
Help?
<!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>
<link href='http://fonts.googleapis.com/css?family=Ruthie' rel='stylesheet' type='text/css'>
<!-- Design by Free CSS Templates http://www.freecsstemplates.org Released for free under a Creative Commons Attribution 2.5 License Name : Portraiture Description: A two-column, fixed-width design with dark color scheme. Version : 1.0 Released : 20130111 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>title</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery.slidertron-1.1.js"></script>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600%7CArchivo+Narrow:400,700" rel="stylesheet" type="text/css" />
<link href="http://fonts.googleapis.com/css?family=Ruthie" rel="stylesheet" type="text/css" />
<link href="default.css" rel="stylesheet" type="text/css" media="all" />
<!--[if IE 6]> <link href="default_ie6.css" rel="stylesheet" type="text/css" /> <![endif]-->
<link rel="stylesheet" type="text/css" href="active1.css" />
</head>
<body>
<div id="wrapper" class="container">
<div id="header">
<div id="logo">
<h1>maggie braner</h1>
</div>
</div>
<div id="menu">
<ul>
<li class="active">Home</li>
<li>Music Lessons</li>
<li>Pottery</li>
<li>Jazz Band</li>
</ul>
</div>
<div id="banner">
<div id="slider">
<div class="viewer">
<div class="reel">
<div class="slide"> <img src="images/pic01.jpg" alt="" height="570" width="505" /> </div>
<div class="slide"> <img src="images/pic02.jpg" alt="" height="500" width="900" /> </div>
</div>
</div>
</div>
<script type="text/javascript">
$('#slider').slidertron({
viewerSelector: '.viewer',
reelSelector: '.viewer .reel',
slidesSelector: '.viewer .reel .slide',
advanceDelay: 3000,
speed: 'slow'
});
</script>
</div>
<div id="page">
<div id="content">
<h2>Welcome!</h2>
<p> body text here </p>
</div>
<div id="sidebar">
<?php
$your_email ='yourname#your-website.com';// <<=== update to your email address
session_start();
$errors = '';
$name = '';
$visitor_email = '';
$user_message = '';
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$user_message = $_POST['message'];
///------------Do Validations-------------
if(empty($name)||empty($visitor_email))
{
$errors .= "\n Name and Email are required fields. ";
}
if(IsInjected($visitor_email))
{
$errors .= "\n Bad email value!";
}
if(empty($_SESSION['6_letters_code'] ) ||
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
{
//Note: the captcha code is compared case insensitively.
//if you want case sensitive match, update the check above to
// strcmp()
$errors .= "\n The captcha code does not match!";
}
if(empty($errors))
{
//send the email
$to = $your_email;
$subject="New form submission";
$from = $your_email;
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$body = "A user $name submitted the contact form:\n".
"Name: $name\n".
"Email: $visitor_email \n".
"Message: \n ".
"$user_message\n".
"IP: $ip\n";
$headers = "From: $from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to, $subject, $body,$headers);
header('Location: thank-you.html');
}
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact Us</title>
<!-- define some style elements-->
<style>
label,a, body
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
.err
{
font-family : Verdana, Helvetica, sans-serif;
font-size : 12px;
color: red;
}
</style>
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>
<div id='contact_form_errorloc' class='err'></div>
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" value='<?php echo htmlentities($name) ?>'>
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" value='<?php echo htmlentities($visitor_email) ?>'>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message" rows=8 cols=30><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
<label for='message'>Enter the code above here :</label><br>
<input id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
var img = document.images['captchaimg'];
img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
</body>
</html>
</div>
</div>
</div>
<div id="footer">
<p>Copyright (c) 2012 Sitename.com. All rights reserved. Design
by FreeCSSTemplates.org,</br>
released under a <a href="http://creativecommons.org/licenses/by/3.0/">Creative
Commons Attributions 3.0</a> license</p>
</div>
</div>
</body></html>
i think you must put the session_start() in the very top of your page
RESOLVED.
I renamed the file from .html to .php and it worked fine as is.
Thank you all.

PHP logic error in a php form code

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.

Convert WebsiteField to emailField

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.

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