Итак, после того, как я прочитал ваш первоначальный пост, я сделал ОБНОВЛЕНИЕ кода (в попытке сделать его более простым для чтения), насколько я понимаю, потому что, опять же, я новичок в этом. И, оглядываясь назад, это может быть проблемой. Поэтому я ценю ваше терпение; пожалуйста, не убивайте меня … Вот что я изменил и протестировал на сервере:
Вот фактическая веб-страница (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><a href="index.php">Home</a></li>
<li><a href="AboutUs.php">About</a></li>
<li><a href="Location.php">Location</a></li>
<li><a href="GroomingServices.php">Grooming</a></li>
<li><a href="ContactUs.php">Contact Us</a></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>
Затем я изменил файл действия (contact.php) на:
<?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"=>"[email protected]","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.");
}
}
?>
Итак, этим утром я вернулся и применил реальные изменения, как вы предложили. Проблема в том, что я получаю синтаксическую ошибку в строке 140 в теге php после закрывающего тега html. у него проблема с одним из закрывающих скобок. Вот этот код, который будет новой веб-страницей (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="https://web-answers.ru/wp-content/uploads/2019/02/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><a href="PSTP.html">Home</a></li>
<li><a href="AboutUs.html">About</a></li>
<li><a href="Location.html">Location</a></li>
<li><a href="GroomingServices.html">Grooming</a></li>
<li><a href="ContactUs.html">Contact Us</a></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><a href="http://www.hillsidevetclinic.org">Hillside Vet Clinic</a></li> <li><a href="http://www.petsmart.com">PetSmart Stores</a></li> <li><a href="http://www.poochhotel.com">Pooch Hotel</a> </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));
}
?>
А вот новый файл сообщения (ContactProcess.php) в соответствии с вашим предложением:
<?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"=>"[email protected]","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.");
}
}
Я не проверял этот второй код; но сделаю это и дам тебе знать, что я найду; а пока что есть какие-либо советы по поводу пересмотренного / обновленного кода выше? В очередной раз благодарим за помощь …
Попробуйте разбить часть своей логики на маленькие функции, чтобы легче было отслеживать задачи. Также для формы, попробуйте использовать проверку формы через JQuery:
страница формы:
<!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="https://web-answers.ru/wp-content/uploads/2019/02/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><a href="PSTP.html">Home</a></li>
<li><a href="AboutUs.html">About</a></li>
<li><a href="Location.html">Location</a></li>
<li><a href="GroomingServices.html">Grooming</a></li>
<li><a href="ContactUs.html">Contact Us</a></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><a href="http://www.hillsidevetclinic.org">Hillside Vet Clinic</a></li> <li><a href="http://www.petsmart.com">PetSmart Stores</a></li> <li><a href="http://www.poochhotel.com">Pooch Hotel</a> </div>
</body>
</html>
Функции, необходимые в контактной форме:
// 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"=>"[email protected]","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.");
}
}
Других решений пока нет …