How can we pass FORM data from included file to another page? - php

I had included footer.php in index file and the footer contains FORM for Subscriber Register.
when i click to submit a new subscriber email from https://mywebsite.com/index.php the value is not being passed from index.php page the same code is perfectly apply when i use url https://mywebsite.com/footer.php
footer.php
<form id="newsletterForm" action="newsletter-subscribe.php" method="POST">
<div class="input-group input-group-rounded">
<input name="mailid" type="email" placeholder="Email Address">
<span>
<input type="submit">
</span>
</div>
</form>
newsletter-subscribe.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["mailid"];
$recipient = "info#myemail.com";
$email_content = "
<html>
<body>
<h2>Hello You had a new Subscriber!</h2>
<h3>Email Id : ".$email." </h3>
</body>
</html>
";
$email_headers = "MIME-Version: 1.0" . "\r\n";
$email_headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$email_headers .= 'From: info#myemail.com' . "\r\n";
if (mail($recipient, $subject, $email_content, $email_headers)) {
$msg= "Thanks You! For Subscribing our service.";
echo "<script type='text/JavaScript'>;window.location.href='../index.php';</script>";
} else {
$error= "Faild To Send Your Order. Please Try Again.";
echo "<script type='text/JavaScript'>alert ('$error');window.location.href='index.php';</script>";
}
} else {
$error1= "There was a problem with your submission, please try again.";
echo "<script type='text/JavaScript'>alert ('$error1');window.location.href='index.php';</script>";
}
?>

Related

PHP success message on same page / styling

I am new to PHP but found a tutorial for a php contact form. the form works well except the 'your email was sent successfully' text shows on a new page.
Is there a way to make it so the text shows on the same page?
I am also unsure how I would go about styling the information?
thanks
<?php
$to = 'zoeharrisondesign#gmail.com';
$subject = 'New Message Recieved!';
$from = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$name = $_POST['name'];
//check honeypot
if( !empty( $honeypot ) ) {
echo 'There was a problem';
}
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = "$message \r\n |
From $name \r\n |
Tel: $phone";
// Sending email
if(mail($to, $subject, $message, $headers)){
echo 'Your mail has been sent successfully.';
} else{
echo 'Unable to send email. Please try again.';
}
?>
HTML
<form role="form" action="action.php" method="post" class="contact-form">
<div class="form-row"><input type="text" id="name" name="name" placeholder="name" required="required"></div>
<div class="form-row"><input type="email" id="email" name="email" placeholder="email" required="required"> </div>
<div class="form-row"><input type="tel" id="phone" name="phone" placeholder="phone"></div>
<div class="form-row"><textarea id="message" name="message" placeholder="message" required="required" style="height:200px"></textarea></div>
<div class="form-row" style="display:none;">
<input type="hidden" name="url" placeholder="URL"></div>
<div class="form-row"><input class="submit" type="submit" value="Send"></div>
</form>
An easy way of doint that is using sessions,
you need to create a session php file like just this:
SESSION.PHP:
ini_set('session.use_only_cookies', 1);
session_set_cookie_params(0,'/','localhost',false,false); // IF YOU ARE HOSTING IT IN LOCAL
session_start();
session_regenerate_id(); // REGENERATE SESSIONE FOR SECURITY ISSUES
MAIL PHP FILE:
// add this on top of your mail.php file
include 'session.php'; // just insert the path of the file
// AND CHANGE THIS
if(mail($to, $subject, $message, $headers)){
$_SESSION['error'] = 'Your mail has been sent successfully.'; // setting your session and value
header("Location: index.php"); // path of the file where you want to show the text
exit();
} else{
// same thing
}
INDEX.PHP: (just add this where you want to show the text, example:)
if(isset($_SESSION['error'])) {
echo '<h1>'.$_SESSION['error'].'</h1>';
unset($_SESSION['error']); // to display it just once and then delete it
}
IMPORTANT: you need to add also <?php include 's-session.php'; ?> to the top of your index.php file
In top of php code start the session`session_start();`
Insert this piece of code
if(mail($to, $subject, $message, $headers)){
$_SESSION['message'] = "Submitted Successfully";
}
Paste this code in html where you want to show the message
<?php if (isset($_SESSION['message'])): ?>
<div class="msg text-success" id="success" >
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>

How to collect email in form (html) and send to external email using (PHP)?

I have a question with my code. I created a form for collecting emails.
enter image description here
In my html I used the <form> tag to reference signup.php
HTML: (form part)
<form method="post" action="php/signup.php" name="cform" id="cform">
<div class="form-row">
<div class="col-12 col-md-9 mb-2 mb-md-0">
<input name="email" id="email" type="text" class="form-control form-control-lg" placeholder="Enter your email...">
</div>
<div class="col-12 col-md-3">
<button type="submit" class="btn btn-block btn-lg btn-primary">Sign up!</button>
</div>
</div>
</form>
In my signup.php I tried many different things to get it to send to my email but it doesn't send the email from form to my email with subject. I believe I followed PHP's mail class *mail(sendtoemail,subject,body,headers) format. Thanks!!!
PHP (php/signup.php)
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$email = $_POST['email']
if (trim($email) == '') {
echo 'Please enter a valid email address.';
exit();
} else (!isEmail($email)) {
echo 'You have entered an invalid e-mail address. Please try again.';
exit();
}
$address = "p****#*******tech.mx";
$to_email = "p****#*******tech.mx";
$e_body = "You have been contacted by $email" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact them via $email";
$message = wordwrap ($e_body . $e_reply, 70);
$headers = "From: $address" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($to_email, $e_subject, $message, $headers)) {
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to Renovatio.</p>";
echo "</div>";
echo "</fieldset>";
}
else {
echo 'ERROR!';
}
?>
First, you need to assign a value to e_subject, because according to your code, e_subject is empty. And then remember that sometimes and depending on which host service you have, only authenticated accounts can send emails, preventing spam. Think about use a lib like PHPMailer

Upon submitting form, scroll to vertical position on page

I have created a simple html/php form where visitors on my site can write their name, email and message and then send the message to my email. Problem is that when they submit the email, my site then performs a full refresh (it looks like) and therefore just reloads to the top of my site. I would like for the user to remain at the same scroll position after submit, so that they can instantly see whether the submit was succesful or not. So either a solution that prevents the refresh or some other solution that automatically scrolls down vertical to the form.
Can you tell me if this is possible using php? Or do I have to use some jquery/ajax solution?
Below is the code I am using. I am a complete novice, so please be gentle.
<form action="" method="post" id="form">
<div class="contact-info-group">
<label for="name"><span>Your name</span>
<input type="text" id="name" name="name" autocomplete="off" value="<?php echo $name; ?>"></label>
<label for="email"><span>Your email</span>
<input type="email" id="email" name="email" autocomplete="off"></label>
</div>
<label for="message"><span>Your message</span>
<textarea id="message" name="message"></textarea></label>
<input id="button1" type="submit" class="button next" name="contact_submit" value="Send message">
<?php
// Check for header injections
function has_header_injection($str) {
return preg_match("/[\r\n]/", $str);
}
if (isset ($_POST['contact_submit'])) {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$msg = $_POST['message'];
// Check to see if $name or $email have header injections
if (has_header_injection($name) || has_header_injection($email)) {
die();
}
if (!$name || !$email || !$msg) {
echo '<div class="contact-warning"><h2>! Error - Please note that all of the above fields are required !</h2></div>';
exit;
}
// Add the recipient email to a variable
$to = "email#email.com";
// Create a subject
$subject = "Message via website.com - $name";
// Construct the message
$message = "Name: $name\r\n";
$message .= "Email: $email\r\n";
$message .= "Message: \r\n\r\n$msg";
// Clean up the message
$message = wordwrap($message, 72);
// Set the mail headers into a variable
$headers = "MIME-Version 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email> \r\n";
$headers .= "X-Priority: 1\r\n";
$headers .= "X-MSMail-Priority: High\r\n\r\n";
// Send the email
mail($to, $subject, $message, $headers);
echo '<div class="contact-warning"><h2>Thank you for your message. We will get back to you shortly.</h2></div>';
}
?>
</form>

mail function returns false

It has been asked multiple times here, but I can't find the answer.
I've tried to add headers etc but nothing seems to work.
My code returns "false" everytime I try to send the mails.
<?php
if(isset($_GET['action'])=='submitfunc') {
$EmailTo = prep($sObj->email);
$Subject = "The reason why your submission got rejected.";
$Message = Trim(stripslashes($_POST['Message']));
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <webmaster#website.com>' . "\r\n";
// prepare email body text
$Body = "";
$Body.= "Message: ";
$Body.= $Message;
// send email
$success = mail($EmailTo,$Subject,$Body,$headers);
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=succes.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
}else { ?>
<div class="emailrejection">
<form method="post" action="?action=submitfunc">
Dear <?php prep($sObj->username); ?>, <br>
<textarea placeholder="Describe why the image got rejected...." name="Message" rows="3" cols="20" id="Message"></textarea> <br>
All the best,,<br>
Moderator <?php prep($uObj->username); ?><br>
<input type="submit" name="submit" value="No + send message" class="btn btn-large btn-danger" />
</form>
</div>
I think the error is in line 3.
$EmailTo = prep($sObj->email);
If I replace this with:
$EmailTo = "myemail.gmail.com"; everthing works fine.
If I echo $EmailTo it also works fine. Why can't this be handeled in the mail function?

PHP mail script not sending textarea and duplicating everything else in body

Im trying to send an e-mail with the following script I've made. But seem to encounter a weird problem that I need help with.
The mail script
// Get field values.
$name = strip_tags($_POST["name"]);
$email = strip_tags($_POST["email"]);
$message = $_POST["msg"];
// Check if e-mail address is valid.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set e-mail and subject.
$to = "mail#mydomain.dk";
$subject = "You have a new message.";
// Set header values.
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Set request body.
$message = "<html>";
$message .= "<body>";
$message .= "<p><b>From:</b><br>" . $name . "</p>";
$message .= "<p><b>Email:</b><br>" . $email . "</p>";
$message .= "<p><b>Message:</b><br>" . $message . "</p>";
$message .= "</body>";
$message .= "</html>";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
} else {
echo "Invalid Email, please provide an correct email.";
}
The HTML
<form id="contact-form" data-toggle="validator" data-disable="true" role="form">
<div class="form-group">
<label for="name">Navn</label>
<input type="text" name="name" id="contact-name" class="form-control" data-minlength="2" data-error="Please provide a valid name." required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" name="email" id="contact-email" class="form-control" data-minlength="5" data-error="Please provide a valid e-mail address." required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="message">Your message:</label>
<textarea name="msg" id="contact-email" data-minlength="10" data-error="Your message must be at least 10 characters long." class="form-control" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button id="submit" value="send" class="btn btn-primary">Send</button>
<div id="success"></div>
</div>
</form>
The Javascript
$(document).ready(function(){
$('#success').css('display', 'none');
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
url: "php/form.php",
data: $("#contact-form").serialize(),
type: 'POST',
statusCode: {
500: function(data) {
$('#success').css('display', 'none');
$('#success').css('color', '#A94442');
$('#success').html('Your message was not sent.');
$('#success').fadeIn(200);
},
404: function(data) {
$('#success').css('display', 'none');
$('#success').css('color', '#A94442');
$('#success').html('Your message was not sent.');
$('#success').fadeIn(200);
},
200: function(data) {
console.log(data);
$('#success').css('display', 'none');
$('#success').css('color', '#74C274');
$('#success').html('Your message was sent.');
$('#success').fadeIn(200);
}
}
});
});
});
The e-mail is sent and received, but the textarea is not getting sent through, and it seems to sent the "email" and "name" field twice in the message body.
The e-mail output looks like this:
From:
Someone
Email:
someone#someone.com
Besked:
From:
Someone
Email:
someone#someone.com
Help will be very much appreciated. Have been trying to fix this for hours now.
The error is located here :
$message .= "<p><b>Message:</b><br>" . $message . "</p>";
You are using the same variable for the message to be sent and the message received by your PHP.
This code will be working :
// Get field values.
$name = strip_tags($_POST["name"]);
$email = strip_tags($_POST["email"]);
$message_text = $_POST["msg"];
// Check if e-mail address is valid.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set e-mail and subject.
$to = "mail#mydomain.dk";
$subject = "You have a new message.";
// Set header values.
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Set request body.
$message = "<html>";
$message .= "<body>";
$message .= "<p><b>From:</b><br>" . $name . "</p>";
$message .= "<p><b>Email:</b><br>" . $email . "</p>";
$message .= "<p><b>Message:</b><br>" . $message_text . "</p>";
$message .= "</body>";
$message .= "</html>";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
} else {
echo "Invalid Email, please provide an correct email.";
}

Categories