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.
Related
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 5 years ago.
I have just started learning PHP and was trying to create a responsive contact form using PHP.
But the problem is that my PHP code gets printed as it is on the web page as it is and not in the required format as I need it.
Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Contact Us</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-
ui.min.js"></script>
</head>
<body>
<!-- <img src="call.jpg" id="background"> -->
<div id="container-fluid">
<div class="row">
<div class="col-sm-offset-1 col-sm-10 contactform">
<h1>Contact Us:</h1>
<?php
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$message = $_REQUEST["message"];
$submit = $_REQUEST["submit"];
$to = "abc1996#xyz.com";
$var = rand(1,1000);
$subject = 'Complaint Registered. Complaint No.: '. echo "$var";
if($submit)
{
if(!$name)
$errors = $errors."<p><strong>Name missing!</strong></p>";
else
$name = filter_var($name,FILTER_SANITIZE_STRING);
if(!$email)
$errors = $errors."<p><strong>Email missing!</strong></p>";
else
{
$name = filter_var($email,FILTER_SANITIZE_STRING);
if(!filter_var($email,FILTER_VALIDATE_EMAIL))
{
$errors = $errors."Please give a valid Email-Address!";
}
}
if(!$message)
{
$errors = $errors."<p><strong>Message box can't be empty!</strong></p>";
}
else
{
$message = filter_var($message,FILTER_SANITIZE_STRING);
}
if($errors)
{
$finalmsg = "<div class='alert alert-danger'> ".$errors "</div>";
}
else
{
$date = date('d MM YY');
$content = "Hi $name. Thank you for your complaint. Your complaint has been registered on $date and your complaint number is: $var";
if(mail($to, $subject, $content))
{
$finalmsg = '<div class="alert alert-success">Your mail has been sent and we will REQUEST back to you asap</div>';
}
else
{
$finalmsg = '<div class="alert alert-warning">Error Sending Mail. Try again later!</div>';
}
}
echo $finalmsg;
}
?>
<form action="" method="post">
<div class="form-group">
<label for="name">Name *: </label>
<input type="text" name="name" id="name" placeholder="Enter your Name " class="form-control">
</div>
<div class="form-group">
<label for="email">Email *:</label>
<input type="email" name="email" id="email" placeholder="Enter your Email " class="form-control">
</div>
<div class="form-group">
<label for="message">Message *:</label>
<textarea id="message" name="message" class="form-control" rows="5"></textarea>
</div>
<input type="submit" name="submit" class="btn btn-success btn-lg" value="Send Message" id="submit">
</form>
</div>
</div>
</div>
</body>
Also, it would be great if you help me in generating a random number and use it in my code. I have tried it in my code, please tell me whether it is correct or not.
Thank You
Is this page served by a web server and does it have a .php extension?
PHP is a preprocessor which means that it needs to be run by a web server. Try WAMP (Windows) or MAMP (for Mac), rename your file to .php and retry.
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 have a process.php file for processing a comment/message form. If there is an error during the processing, the incorrect form content is echoed and shown as a web page named process.php to the viewer for correction and resubmitting.
The problem is that I need the echoed content to contain various <?php include("xxxx.php");?> elements so that it matches the rest of my site. But this seems to make the page fall over (showing blank page with no content). I've been told that I should use either include("xxxx.php"); or echo file_get_contents("xxxx.php"); from within the echoed content, but neither displays the intended content.
Any help in these issues would be greatly appreciated.
Code: (some items xxxxx for security)
<?php
// Information to be modified
$your_email = "xxxxxxxx#xxxxx.xx.xx"; // email address to which the form data will be sent
$subject = "Contact message"; // subject of the email that is sent
$thanks_page = "thankyou.htm"; // path to the thank you page following successful form submission
$contact_page = "mail_form_styled.php"; // path to the HTML contact page where the form appears
// Nothing needs to be modified below this line
if (!isset($_POST['submit'])) {
header( "Location: $contact_page" );
}
if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = trim($_POST["email"]);
$com = $_POST["comments"];
$spa = $_POST["spam"];
if (get_magic_quotes_gpc()) {
$nam = stripslashes($nam);
$ema = stripslashes($ema);
$com = stripslashes($com);
}
$error_msg=array();
if (empty($nam) || !preg_match("~^[a-z\-'\s]{1,60}$~i", $nam)) {
$error_msg[] = "The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}
if (empty($ema) || !filter_var($ema, FILTER_VALIDATE_EMAIL)) {
$error_msg[] = "Your email must have a valid format, such as name#mailhost.com";
}
$limit = 1000;
if (empty($com) || !preg_match("/^[0-9A-Za-z\/-\s'\(\)!\?\.,]+$/", $com) || (strlen($com) > $limit)) {
$error_msg[] = "The Comments field must contain only letters, digits, spaces and basic punctuation ( ' - , . ), and has a limit of 1000 characters. Website addresses can not be included.";
}
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the spam test!";
exit ();
}
// Assuming there's an error, refresh the page with error list and repeat the form
if ($error_msg) {
echo '<!DOCTYPE html>
<html lang="en">
<!-- Begin head items -->
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1">
<meta name="description" content="The Dark Fortress contact form. Use it to get in touch…" />
<link href="../styles/screen.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="alternate" type="application/rss+xml"
title="thedarkfortress Command Briefing"
href="http://feeds.feedburner.com/ThedarkfortressCommandBriefing" />
<title>O dear! | The Dark Fortress</title>
<style type="text/css">
.hide {display:none;}
</style>
</head>
<!-- Begin body items -->
<body>
<div id="container">
<!-- Begin header items -->
echo file_get_contents("../components/header.php");
<!-- Begin main content items -->
<div id="content-container">
<!-- Begin content items -->
<div id="content">
<h1>O dear!</h1>
<p>Unfortunately, your message could not be sent. The form as you filled it out is displayed below. Make sure each field completed, and please also address any issues listed below:</p>
<ul class="err">';
foreach ($error_msg as $err) {
echo '<li>'.$err.'/li>';
}
echo '</ul>
<form method="post" action="', $_SERVER['PHP_SELF'], '">
<label for="name">Name</label>
<input name="name" type="text" size="40" maxlength="60" id="name" value="'; if (isset($_POST["name"])) {echo $nam;}; echo '">
<label for="email">Email Address</label>
<input name="email" type="email" size="40" maxlength="60" id="email" value="'; if (isset($_POST["email"])) {echo $ema;}; echo '">
<label for="comm">Comments</label>
<textarea name="comments" rows="7" cols="50" id="comm">'; if (isset($_POST["comments"])) {echo $com;}; echo '</textarea>
<div class="hide">
<label for="spam">What is six plus four?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
<input type="submit" name="submit" value="Send" class="button orange send" />
</form>
<div class="divider"><hr /></div>
<p><img src="../main_assets/isiah_page_sig_flat.png" alt="Isiah signature" /></p>
<p><strong>Chronicler Isiah,</strong> the 4th Battle Company, Dark Angels.</p>
</div>
<!-- Begin left nav items -->
<div id="leftnav">
echo file_get_contents("../components/hq_leftnav.php");
</div>
</div>
</div>
<!-- Begin footer items -->
echo file_get_contents("../components/footer.php");
<!-- Begin google analytics tracker items -->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("xxxxxx"); pageTracker._trackPageview();
</script>
</body>
</html>';
exit();
}
$email_body =
"Name of sender: $nam\n\n" .
"Email of sender: $ema\n\n" .
"COMMENTS:\n\n" .
"$com" ;
// Assuming there's no error, send the email and redirect to Thank You page
if (isset($_REQUEST['comments']) && !$error_msg) {
mail ($your_email, $subject, $email_body, "From: $nam <$ema>" . "\r\n" . "Reply-To: $nam <$ema>");
header ("Location: $thanks_page");
exit();
}
}
You'd simply use CSS as you normally would...
<?php
// index.php
?>
<!doctype html>
<html>
<head>
<style type="text/css">
.myClass {
color: #f00;
}
</style>
</head>
<body>
<?php
include('myFile.php');
?>
</body>
</html>
<?php
// included myFile.php
echo '<p class="myClass">Echoed content!</p>';
If you're ending up with a blank page with no content then you potentially have errors in your PHP. Ensure error reporting is enabled and you'll be able to see what's going wrong.
I've managed to make the name/email form with redirect function on submit to work. The only problem now is that when the redirect page loads, I get the form input on the top of it (name and email).
Anyone got the idea where did I flunk?
<!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="style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function submitForm() {
var form = document.forms[0];
if (form.name.value == '') { alert("Name?"); return; }
if (form.email.value == '') { alert("Email?"); return; }
apos = form.email.value.indexOf("#");
dotpos = form.email.value.lastIndexOf(".");
if (apos < 1 || dotpos - apos < 2) { alert("Correct email?"); return; }
form.submit();
}
</script>
<script src="fancybox/jquery.fancybox-1.3.1.pack.js" type="text/javascript"></script>
<link rel="stylesheet" href="fancybox/jquery.fancybox-1.3.1.css" type="text/css" media="screen"/>
<script type="text/javascript">
function PopIt() {
$("a#trigger").trigger('click');
window.onbeforeunload = UnPopIt;
return "Dont go.";
}
function UnPopIt() { /* nothing to return */ }
$(document).ready(function() {
window.onbeforeunload = PopIt;
$("a#trigger").fancybox({
'hideOnContentClick': false,
'showCloseButton': false
});
$("a[id!=trigger]").click(function(){ window.onbeforeunload = UnPopIt; });
});
</script>
</head>
<body>
<div style="display: none;">
<a id="trigger" href="#popup"> </a>
<div id="popup">
<div style="background-color:#ff3300;">
<form method="post" action="page2.php" name="popups" id="popups">
<fieldset>
<label for=name><span class="required">*</span> Name</label>
<br />
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for=email><span class="required">*</span> Email</label>
<br />
<input name="email" type="text" id="email" size="30" value="" />
<br />
<input type="button" value="Submit" class="btn" onclick="submitForm();">
</fieldset>
<br />
</form>
</div>
</div>
</div>
<div id="content">Fa la la la la</div>
</div>
</body>
</html>
and when the visitor enters the data (in the popup window, triggered on exit), after hitting the submit button the form redirects to here;
<?
if($_POST['name']!="" and $_POST['email']!=""){
$headers = "From: Acme";
$message =
strtoupper($_POST['name'])."
".strtoupper($_POST['email'])."
";
echo str_replace("\n","<br />", $message);
$headers2 = "From: Acme <ceo#acme.com>\nContent-Type: text/plain; charset=UTF-8; format=flowed\nMIME-Version: 1.0\nContent-Transfer-Encoding: 8bit\nX-Mailer: PHP\n";
$message2 = "
Hello ".($_POST['name'])."
";
mail("ceo#acme.com", "Freebies", $message, $headers);
mail("$_POST[email]", "Gesundheit!", $message2, $headers2);
$myFile = "free.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "$_POST[name]*$_POST[email]*".$_SERVER['REMOTE_ADDR']."*".date("d-m-Y H:i")."
";
fwrite($fh, $stringData);
fclose($fh);
}
?>
<!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="style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setTimeout(function(){
$("div#md").fadeIn("slow", function () {
});
}, 1000);
});
</script>
</head>
<body>
<div id="top"><img src="top.png" /></div>
<div id="wrapper" style="height:900px;">
<div id="content">Whoo-eee</div>
</div>
</body>
</html>
But I dont see how or why is there the form info (name and email) shown on the top of this page2.php...
echo str_replace("\n","<br />", $message);
comment out this line on page2
You have this line
echo str_replace("\n","<br />", $message);
near the top of page 2, so you are echoing the message which is comprised of the name and email
I'm having an issue with my php code. I'm using jquery to validate user input. When I click the submit button I recieve the email, but I cannot return to another page such as "it was successfully sent". I'm new to this and I'm not sure how to get help so I'm going to post the php page where it sends and where I cannot cant that it done so T.T
this page is called ajax.php
<?
#extract($_POST);
$name = stripslashes($name);
$email = stripslashes($email);
$telephone = stripslashes($telephone);
$message = stripslashes($message);
if(mail("mememe#hotmail.com","Email from $name","
$message
(From $name, $email, $telephone)","From: $email")){
echo "$name $email $telephone $message";
}
echo "Email Successfully Sent!<br />
<br />
Name: $name<br />Email: $email<br />telephone: $telephone<br />Message: $message";
?>
this page is the form with jquery validation "onblur" which im submitting from
<!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>
<title>Contact Us</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="../style.css" rel="stylesheet" type="text/css" />
<script src="prototype.js" type="text/javascript"></script>
<script src="livevalidation.js" type="text/javascript"></script>
</head>
<body>
<div class="main">
<div class="footer_resize">
<div class="footer">
<div class="menu">
<ul>
<li>Home </li>
<li>Services</li>
<li>Contact Us</li>
</ul>
</div>
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
<div class="body">
<div class="body_resize">
<div class="left">
<h2>Contact for appointment</h2>
<p>
<strong>Address</strong>
<br />So Shiq Studio
<br />380 King Street North
<br />Waterloo ON
<br />Tel. 519.721.8060
<br /></p>
<p></p>
<p><strong>Hours of Operation</strong><br />
Tuesday: 10AM – 7PM <br />
Friday: 10AM – 8PM <br />
Saturday: 9AM – 3PM</p>
<p></p>
<p><strong>Private Appointments</strong><br />
Monday - Wednesday <br />
Colour Upon Consultation <br />
*Minimum 2 Services*</p>
<p><br />
</p>
<p>
<strong></strong><br />
</p>
</div>
<br /><br /><br />
<form id="my-form" style="padding-left:16.9em" >
<table class=shadow border="0" width="71%" style="background:#ececec; font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;" cellspacing="15">
<tr align="left"><td><strong>Full Name</strong></td><td><input type="text" size="50" id="name" name="name" style="font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;"></td></tr>
<tr align="left"><td><strong>Email Address</strong></td><td><input type="text" size="50" id="email" name="email" style="font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;"></td></tr>
<tr align="left"><td><strong>Phone Number</strong></td><td><input type="text" size="50" id="telephone" name="telephone" style="font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;"></td></tr>
<tr align="left"><td valign="top"><strong>Comments</strong></td><td><textarea id="message" name="message" rows="8" cols="80" style="font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;"></textarea></td></tr>
<tr align="left"><td> </td><td>
<input type="button" name:"clear" value="Send" onclick="sendRequest();" style="font:normal 12px Arial, Helvetica, sans-serif; color:#6b6b6b;font-weight:bold;"/></td></tr>
</table>
</form>
<script type="text/javascript">
var name = new LiveValidation( 'name' );
name.add( Validate.Presence );
var email = new LiveValidation( 'email' );
email.add( Validate.Presence );
email.add( Validate.Email );
var telephone = new LiveValidation( 'telephone' );
telephone.add( Validate.Presence );
telephone.add( Validate.Telephone );
var message = new LiveValidation( 'message' );
message.add( Validate.Presence );
function sendRequest(){
if(LiveValidation.massValidate( [ name, email, telephone, message ] )){
new Ajax.Request('ajax.php',
{
method:'post',
parameters: $('my-form').serialize(true),
onLoading: function(){
$('update_div').show();
$('update_div').innerHTML = "Sending...";
},
onSuccess: function(transport){
var response = transport.responseText || "No response text";
$('update_div').innerHTML = response;
},
onFailure: function(){
$('update_div').innerHTML = "Something went wrong...";
}
});
}
}
</script>
<br /><br /><br /><br />
<div class="clr"></div>
</div>
</div>
<div class="clr"></div>
<div class="clr"></div>
<div class="footer">
<div class="footer_resize">
<p class="leftt">
<img src="../images/rss_1.gif" alt="picture" width="18" height="16" border="0" />
<img src="../images/rss_2.gif" alt="picture" width="18" height="16" border="0" />
</p><p class="right"> © Copyright COSMO STEFAN All Rights Reserved </p>
<div class="clr"></div>
</div>
<div class="clr"></div>
</div>
</div>
</body>
</html>
ive tried what u both below suggested but i cannot get it working T.T. i know the code is messy, im really new to this and just trying to figure out what im doing wrong.. thank u soo much for ur help already.
Update
Using header()
To redirect a page using PHP, you use the header() function. This function is designed to send HTTP headers back to the client. If you send the HTTP Location header with a value, the client will more or less interpret that as meaning "Go to the page specified in the value".
To use the header function to redirect:
<?php
header('Location: http://www.yoursite.com/the/page/you/want/to/go/to.php?success=1');
exit();
?>
Note that I explicitly say exit() after issuing the call to header(). Any code after the header redirect will still be executed unless you exit.
Using $_GET
_GET is a superglobal in PHP. When PHP loads, it loads all of the variables it finds in the URL into this associative array. The example above sets a GET variable named success equal to 1. You can access the GET superglobal like this:
echo( $_GET['success'] );
You can use this to tell your calling page that your email has been sent by just checking to see if $_GET['success'] is set and equal to 1, then output your message.
<?php
if(isset($_GET['success']) && $_GET['success'] == 1)
echo( 'Email Successfully Sent!<br />' );
?>
There are more complicated ways of doing this, but this I believe is probably the easiest and quickest to implement. Be sure not to output anything before you issue the call to the header() function.
I have tidy up your code below. It should work
<?
#extract($_POST);
$name = stripslashes($name);
$email = stripslashes($email);
$telephone = stripslashes($telephone);
$message = stripslashes($message);
if(mail("mememe#hotmail.com","Email from". $name.$message))
{
echo "Email Successfully Sent!<br /><br />Name:". $name."<br />Email:". $email."<br />telephone:". $telephone."<br />Message:". $message;
}
?>
If you want to redirect to success page this is the code
<?
#extract($_POST);
$name = stripslashes($name);
$email = stripslashes($email);
$telephone = stripslashes($telephone);
$message = stripslashes($message);
if(mail("mememe#hotmail.com","Email from". $name.$message))
{
//echo "Email Successfully Sent!<br /><br />Name:". $name."<br />Email:". $email."<br />telephone:". $telephone."<br />Message:". $message;
header("location:http://www.yourdomain.com/success.html");
}
?>