i've search here but i didnt find anything that solve the problem... hope someone could help me please....
i'm using PHPMailer to send mails and i want to add option to attach PDF Files that's my code:
HTML (simplfied):
<form method="post" action="contact/submit.php">
<input type="email" name="email" value="<?php echo $supmail; ?>" size="80">
<input type="text" name="ccmail" value="<?php echo implode(', ', $final);?>" size="80">
<input type="text" style="font-size:11" name="subject" id="subject" value="ORDER" size="80">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input type="file" name="userfile" size="55" style="font-size:10;" accept="application/pdf">
<textarea rows="7" name="message" id="message" cols="85" style="font-size: 11"><?php echo $newstr; ?></textarea>
<div class="g-recaptcha" style="text-align:center;" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>">
<button class="button">Send</button>
</form>
submit.php:
<?php
require('db.php');
$target_dir = __DIR__."/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (file_exists($target_file)) {
echo "קובץ קיים.";
$uploadOk = 0;
}
if($imageFileType != "pdf") {
echo "ניתן להעלות רק קבצי PDF";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "הקובץ לא עלה.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo $target_file;
} else {
echo "שגיאה בהעלאת הקובץ";
}
}
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
redirectWithError("The form must be submitted with POST data.");
}
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
redirectWithError("נא להשלים בדיקת רובוט");
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'לא נשלח קוד.',
'invalid-input-secret' => 'הקוד לא נכון.',
'missing-input-response' => 'לא נשלח אימות.',
'invalid-input-response' => 'שגיאה בקבלת תשובת אימות.',
'bad-request' => 'שגיאה לא ידועה.',
'timeout-or-duplicate' => 'פג תוקף, נסה שוב',
];
$errorMessage = $recaptchaErrorMapping[$error];
redirectWithError("יש לנסות שוב אימות: ".$errorMessage);
}
if (empty($_POST['email'])) {
redirectWithError("אנא הזן כתובת דואר אלקטורני עבור הספק");
}
if (empty($_POST['subject'])) {
redirectWithError("אנא הזן נושא להזמנה");
}
if (empty($_POST['message'])) {
redirectWithError("אנא הזן הודעה לספק");
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
redirectWithError("נא להזין כתובת דואר אלקטרונית חוקית");
}
if (strlen($_POST['message']) < 5) {
redirectWithError("חובה להזין לפחות 5 תויים בהודעה");
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$tomail = $_POST['email'];
$toname = $_POST['suppl'];
$ccmail = $_POST['ccmail'];
$nametoconf = $_POST['confby'];
$orderid = $_POST['orderid'];
$toname2 = "מכללת השף";
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->CharSet = 'UTF-8';
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, $toname2);
$mail->addAddress($tomail, $toname);
$ccmailto = explode(',', $ccmail);
foreach($ccmailto as $ccmailtof)
{
$mail->AddCC($ccmailtof);
}
// Content
$mail->Subject = "".$_POST['subject'];
$mail->Body = <<<EOT
{$_POST['message']}
EOT;
$mail->AddAttachment($target_file);
$mail->send();
redirectSuccess();
} catch (Exception $e) {
redirectWithError("שגיאה בעת ניסיון שליחת ההזמנה: ".$mail->ErrorInfo);
}
?>
when i'm tring to send mail witout the attachment works great.
when i add the attachment i get "Could not access file:"
thank you
This code is unsafe:
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'], $_FILES['userfile']['name']);
As per the file upload example provided with PHPMailer and the PHP docs, you need to validate what's in $_FILES before trusting it.
Further to that, the addAttachment method returns a tru/false status value if it can find and read the file, so check that – don't assume that it's worked.
Related
I have a script for sending emails with PHPmailer (the class is different because I use a CRUD but the functions are the same)
This is the script:
if (array_key_exists('recipient', $_POST)) {
$attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name']));
move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment);
$recipient = $_POST['recipient'];
$subject = $_POST['subject'];
$content = $_POST['content'];
//$attachment = $_POST['attachment'];
$email->Sender = "noreply#fw.net";
$email->Recipient = "noreply#fw.net";
if (!empty($_POST['recipient'])) {
$email->Recipient = $recipient;
} else {
foreach ($bcc as $bcc) {
$email->addBcc($bcc);
}
}
//$email->addRecipient = $bcc;
$email->Subject = $subject;
$email->Content = $content;
$email->addAttachment($attachment, 'MyFile');
$email->Format = "html";
//$email->send();
if(!$email->send()) {
$msg = '<div style="Color:red">Sent:</div>'. $email->SendErrDescription;
} else {
$msg = '<div style="Color:green">not Sent</div>';
header("Refresh:5");
}
}
this the form: email.php (work on the same page script / form)
<form id="mess" action="email.php" method="POST" enctype="multipart/form-data">
<?php if ($Page->CheckToken) { ?>
<input type="hidden" name="<?php echo TOKEN_NAME ?>" value="<?php echo $Page->Token ?>">
<?php } ?>
<div id="jsInfo" data-count="<?php echo $count; ?>"></div>
<div class="card card-primary card-outline">
.......
<div class="form-group">
<div class="btn btn-default btn-file">
<i class="fa fa-paperclip"></i> Allegato
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> <input type="file" name="attachment" id="attachment">
</div>
<p class="help-block">Max. 10MB</p>
</div>
........
<button type="submit" value="Upload" name="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i> Send </button>
I changed the destination to php.ini I use wamp in local for testing
from:
sys_temp_dir = "/tmp"
to
sys_temp_dir = "c:/Users/lt/Documents/Temp"
Question:
Why is not attached to the original file(pdf,jpg,bmp,txt ecc..), but the *.tmp file is attached. ? where am I wrong?
let's say I solved that.
don't works
$attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name']));
move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment);
works
$uploaddir = 'C:/wamp64/www/fw3/';
$attachment_tmp = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
move_uploaded_file($attachment_tmp, $uploaddir . $attachment_name);
I have two problems again ...
1) How to send the attachment to all recipients?
2) When sending a 4Mb file the page loads a lot of time, how can I modify the script to make the sending work in the background?
I am very new to PHP and have been attempting to integrate with mysqli. Apparently on line 19 of my code the variable shown is undefined but as far as I can tell I defined it.
Here is the code. I've look around but I can't really find something to isolate this.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
if(strlen($fname) < 3)
{
$error = "Character name is too short";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Please enter a valid email address";
}
else if(strlen($password) < 8)
{
$error = "Password must be more than 8 characters";
}
else if($password === $passwordConfirm)
{
$error = "Password does not match";
}
else if($image = "")
{
$error = "Please upload an Avatar";
}
else
{
$error = "You have successfully registered";
}
?>
Form Code:
<form method="post" action="index.php" enctype="multipart/form-data">
<label>Character Name:</label><br />
<input type="text" name="fname" /><br /><br />
<label>Email:</label><br />
<input type="text" name="email" /> <br /><br />
<label>Password:</label><br />
<input type="password" name="password" /><br /><br />
<label>Reenter Password:</label><br />
<input type="password" name="passwordConfirm" /><br /><br />
<label>Send us an Avatar:</label><br />
<input type="file" name="image" /><br /><br />
<input type="submit" name="submit" value="submit" />
</form>
if(strlen($fname) < 3) {
$error = "Character name is too short";
}
Here you have the error, $fname is not defined. What you there meaning is $_POST['fname'];. Which you stored in $characterName so change it to:
if(strlen($characterName) < 3){
$error = "Character name is too short";
}
Anyway, cause you define your variables only if isset($_POST['submit']), the lines below will fail if it is not set. Here is a example how it would work.
$_POST['submit'] is only defined if you call it with post parameters (formular, ajax..), so if you directly open the php file it wont work. I added a few comments to make it clear.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit'])) {
//If this block of variable declaration failed it wouldn´t define the variables
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//So we led Php only check the variables if a submit is provided
if(strlen($characterName) < 3) {
$error = "Character name is too short";
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email address";
} else if(strlen($password) < 8) {
$error = "Password must be more than 8 characters";
} else if($password === $passwordConfirm) {
$error = "Password does not match";
} else if($image = "") {
$error = "Please upload an Avatar";
} else {
$error = "You have successfully registered";
}
} else {
//If there is no submit we land here
$error = "No data provided";
}
?>
if submit is not posted then only you receive undefined variables error. In order to avoid those errors. You just change your code like this
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
else
{
$error ="Your submit is not posted.";
exit(); //Without it would again trigger the undefined variables.
}
I'm new to php and wanted to make a simple php script to check a form of my html site.
To answer the questions:
I have a file, that's the Name of the User and I want to check if the password that is in there (line 1) is the same as the one in the "password" field on my site. And when it's like this it should open a site.
Maybe a check if the file exists would be nice :D
This is my php-file, it's named "check.php":
<?php
$f = fopen($_POST["name"], "r");
$theData = fgets($f);
if ($_POST["pw"] == $theData) {
$ch = curl_init("site.com");
curl_exec($ch);
}
fclose($f);
?>
This is my html-file:
<h2>Check</h2>
<form action="check.php" method='post'>
<b>Name: </b><input name="name" type="text" value="Name"> <br>
<b>Password: </b><input name="pw" type="text" value="Passwort"> <br>
<input type="submit" value="Check">
<input type="reset" value="Reset">
</form>
I hope one can help me ^^
I've tried a lot of things now, nothing really worked.
To process a form fields you should do like this in your check.php file(simplest one)
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
if($name == 'admin' && $password == 'admin')
{
header('Location:admin.php');exit;
}else{
echo 'Wrong user name or password';
}
}
may be you are asking to do like this
if(isset($_POST['submit']))
{
$name = $_PSOT['name'];
$password = $_POST['password'];
$file_type = '.txt';
$path = 'path to folder/'.$name.$file_type;
if(file_exists($path))
{
$user_pass = fopen($path, "r");
$flag = 0;
while(!feof($user_pass))
{
$p = fgets($user_pass);
if($password == $p)
{
$flag = 1;
}
}
fclose($user_pass);
if($flag == 1)
{
header('Location:to your page link/weblink');exit;
}else{
echo 'Wrong password';
}
}else{
echo 'User does not exists';
}
}
I have created a web form where people can enter registration information and upload an image to our server. I can get their name, email and message but I can't figure out how to get the uploaded file. I'd like to have the page not reload so that's why I'm using JQuery. It mostly works but I can't get the uploaded file to be recognized in the POST data or the FILES data. The form and processor page are located in the same directory and the image get placed in a subfolder called uploads. Here is what I have so far which does not work for attaching image. I believe the problem is in the JavaScript file where I define the var photoFile = $('#submitForm #photoFile').val(); What is the correct way to declare the uploaded file?
Here's the HTML form:
form action="../inc/sendPhotoEmail.php" name="submitForm" id="submitForm" method="post"
enctype="multipart/form-data">
<label for="submitName">Name <span class="required">*</span></label>
<input name="submitName" type="text" id="submitName" size="35" value="" />
<label for="submitEmail">Email <span class="required">*</span></label>
<input name="submitEmail" type="text" id="submitEmail" size="35" value="" />
<label for="submitMessage">Tell us what you want fixed <span class="required">*</span></label>
<textarea name="submitMessage" id="submitMessage" rows="10" cols="50" ></textarea>
<label for="attach_photo">Attach Your Photo<span class="required"/>*</span></label>
<input type="file" name="photoFile" id="photoFile" accept="image/*"/>
<button class="submit" name="submitFormSubmit" value="Submit">Submit</button>
<span id="image-loader"><img src="images/loader.gif" alt="" /></span>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
The javascript:
jQuery(document).ready(function() {
$('form#submitForm button.submit').click(function() {
$('#image-loader').fadeIn();
var submitName = $('#submitForm #submitName').val();
var submitEmail = $('#submitForm #submitEmail').val();
var submitMessage = $('#submitForm #submitMessage').val();
var photoFile = $('#submitForm #photoFile').val();
var data = 'submitName=' + submitName + '&submitEmail=' + submitEmail +
'&submitMessage=' + submitMessage + $photoFile='+ photoFile;
$.ajax({
type: "POST",
url: "inc/sendPhotoEmail.php",
data: data,
success: function(msg) {
// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#submitForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
}
});
return false;
});
And the PHP file:
<?php
require_once('class.phpmailer.php');
$ourEmail = "repair#myemail.net";
$target_dir = "../uploads/";
if($_POST) {
$name = trim(stripslashes($_POST['submitName']));
$email = trim(stripslashes($_POST['submitEmail']));
$emailMessage = trim(stripslashes($_POST['submitMessage']));
$image_attachment = $_POST["photoFile"]; // <---- this doesn't print anything
$targetFile = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "targetFile = ". $targetFile . "<br/>"; // <-- this only prionts the subdirectory
move_uploaded_file($_FILES["photoFile"]["tmp_name"],$target_dir.$_FILES["photoFile"]["name"]);
echo "Uploaded File :".$_FILES["photoFile"]["name"]. "<br/>";
$target_file = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "target_file = ". $target_file . "<br/>";
$mail = new PHPMailer(); //Create a new PHPMailer instance
$mail->isSendmail(); // Set PHPMailer to use the sendmail transport
// Set Message
$mail->setFrom($email, $name); //Set who the message is to be sent from
$mail->addReplyTo("replyto#example.com", "First Last"); //Set an alternative reply-to address
$mail->addAddress($ourEmail, "Figley T. Whitesides"); //Set who the message is to be sent to
$mail->Subject = "Repair Form Submission"; //Set the subject line
$mail->WordWrap = 80;
$mail->msgHTML($emailMessage); //Create message bodies and embed images
$mail->addAttachment($target_file); //Attach an image file
if (!$error) {
//send the message, check for errors
if (!$mail->send()) {
$mail->ErrorInfo;
} else {
$response = "Photo sent!";
} // end if - no validation error
}
else{
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
$response .= (isset($error['attachment'])) ? $error['attachment'] . "<br />" : null;
echo $response;
} // end if - there was a validation error
}
?>
});
You can't upload data and files with one form using ajax, but try this code,
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
This place has been a real lifesaver at times so thank you all for your efforts in making this place so great. However, I have an issue that I can't find an answer to on here.
I have a website that has a contact form on the home page, and a contact form on some inner pages. I need each one to redirect to a different thank you page (for PPC conversion tracking purposes)
The one on the inner page works fine, submits info and redirects, but the one on the home page only submits info but no redirect. Each form uses a separate php file for the form action and a separate thank you page. Here is the code, can you see a problem? I'm thinking it may be something to do with the headers?
Home Page Code:
<form action="landing-page-form.php" method="post">
<h2>Get A Quote Today!</h2>
<p><label for="name">Name</label><input name="name" id="name"></p>
<p><label for="tel">Tel</label><input name="tel" id="tel"></p>
<p><label for="email">Email</label><input name="email" id="email"></p>
<p><label for="service">Service</label><select name="service" id="service"><option value="Kitchen Design">Kitchen Design</option><option value="Bathroom Design">Bathroom Design</option><option value="Central HEating">Central Heating</option><option value="Appliances">Kitchen Appliances</option><option value="Brochure Request">Free Brochure Request</option><option value="Home Visit Request">Free Home Visit Request</option></select></p>
<p><input type="checkbox" name="chk" id="chk" value="1"> <label class="chk" for="chk">check the checkbox</label></p>
<p><button name="submit" type="submit">Send My Enquiry!</button></p>
</form>
Here is the relating php
<?php if ($_POST) {
header('Content-type: application/json');
$fields = array();
$msg = array();
foreach($_POST as $k=>$v) $_POST[$k] = trim($v);
$pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(preg_match($pattern, $_POST['email'])) $email_ok = true;
else $email_ok = false;
if(!$_POST['email'] || !$email_ok) $fields[] = "email";
if(!$_POST['name']) $fields[] = "name";
if(!$_POST['tel']) $fields[] = "tel";
if(count($fields)) {
$status = "error";
if(!$_POST['name'] || !$_POST['email'] || !$_POST['email']) $msg[] = "Please specify your name, telephone and email address.";
if(!$email_ok) $msg[] = "Provided e-mail address is invalid.";
$message = implode("<br>", $msg);
$response['msgStatus'] = $status;
$response['message'] = $message;
$response['errorFields'] = $fields;
} else {
$mailContent = "Name: {$_POST['name']}\ntel: {$_POST['tel']}\nE-mail: {$_POST['email']}\nService: {$_POST['service']}\nCheckbox: {$_POST['chk']}";
$ok = mail("email#email.com", "Message from Home Page Landing Page Form", $mailContent, "From:<".$_POST['email'].">");
if($ok) {
$response['msgStatus'] = "ok";
header( 'Location: /thanks.php' ) ;
} else {
$response['msgStatus'] = "error";
$response['message'] = "Could not send your request due to an error.";
}
}
echo json_encode($response);
}
?>
Here is the inner page HTML:
<form action="quick-contact-form.php" method="post">
<h6>Quick Contact</h6>
<p><label for="name">Name</label><input name="name" id="name"></p>
<p><label for="tel">Tel</label><input name="tel" id="tel"></p>
<p><label for="email">Email</label><input name="email" id="email"></p>
<p><label for="service">Service</label><select name="service" id="service"><option value="Kitchen Design">Kitchen Design</option><option value="Bathroom Design">Bathroom Design</option><option value="Heating">Central Heating</option><option value="Appliances">Kitchen Appliances</option><option value="Brochure Request">Free Brochure Request</option><option value="Home Visit Request">Free Home Visit Request</option></select></p>
<p><input type="checkbox" name="chk" id="chk" value="1"> <label class="chk" for="chk">check the checkbox</label></p>
<p><button name="submit" type="submit">Send!</button></p>
</form>
And the relating PHP
<?php if ($_POST) {
header('Content-type: application/json');
$fields = array();
$msg = array();
foreach($_POST as $k=>$v) $_POST[$k] = trim($v);
$pattern = "/^[a-zA-Z0-9][a-zA-Z0-9\.-_]+\#([a-zA-Z0-9_-]+\.)+[a-zA-Z]+$/";
if(preg_match($pattern, $_POST['email'])) $email_ok = true;
else $email_ok = false;
if(!$_POST['email'] || !$email_ok) $fields[] = "email";
if(!$_POST['name']) $fields[] = "name";
if(!$_POST['tel']) $fields[] = "tel";
if(count($fields)) {
$status = "error";
if(!$_POST['name'] || !$_POST['email'] || !$_POST['email']) $msg[] = "Please specify your name, telephone and email address.";
if(!$email_ok) $msg[] = "Provided e-mail address is invalid.";
$message = implode("<br>", $msg);
$response['msgStatus'] = $status;
$response['message'] = $message;
$response['errorFields'] = $fields;
} else {
$mailContent = "Name: {$_POST['name']}\ntel: {$_POST['tel']}\nE-mail: {$_POST['email']}\nService: {$_POST['service']}\nCheckbox: {$_POST['chk']}";
$ok = mail("email#email.com", "Message from Website Landing Page Form", $mailContent, "From:<".$_POST['email'].">");
if($ok) {
$response['msgStatus'] = "ok";
header( 'Location: /thankyou.php' ) ;
} else {
$response['msgStatus'] = "error";
$response['message'] = "Could not send your request due to an error.";
}
}
echo json_encode($response);
}
?>
Any and all help, suggestions, feedback appreciated.
First of, check the path you are using and try to make it absolute, not relative.
Second, check your .htaccess file - maybe there's some nasty rewrite rules.
By the way, is it OK that you've got different redirect pages? header( 'Location: /thanks.php' ) ; and header( 'Location: /thankyou.php' ) ;?