Hi Guys
I have got my hands on a great bit of code that works, see below. I have edited it a bit to meet my needs but there is still a few things I would like to do and I don’t know how so I wonder if someone can amend this for me.
I would like to add in a validation to only allow upload of .doc, .docx and .txt files.
I would like to add some text to display in the textarea to describe the type of thing I want the user to type about.
And finally, I would like it to redirect to a page saying thanks for the file, rather than just staying on the same page and displaying a message saying thanks.
Would be very grateful if you could help with this.
Thanks, Adrian
[code]
<?php
/* Mailer with Attachments */
$action = “”;
$action = $_REQUEST[‘action’];
global $action;
function showForm() {
?>
<form enctype=”multipart/form-data” name=”send” method=”post” action=”<?=$_SERVER[‘PHP_SELF’]?>”>
<input type=”hidden” name=”action” value=”send” />
<input type=”hidden” name=”MAX_FILE_SIZE” value=”10000000″ />
<p>Name: <input name=”from_name” size=”50″ /></p>
<p>Email: <input name=”from_email” size=”50″ /></p>
<p>Subject: <input name=”subject” size=”50″ /></p>
<p>Message: <textarea name=”body” rows=”10″ cols=”50″></textarea></p>
<p>Attachment: <input type=”file” name=”attachment” size=”50″ /></p>
<p><input type=”submit” value=”Send Email” /></p>
<?php
}
function sendMail() {
$from_name = stripslashes($_POST[‘from_name’]);
$subject = stripslashes($_POST[‘subject’]);
$body = stripslashes($_POST[‘body’]);
$attachment = $_FILES[‘attachment’][‘tmp_name’];
$attachment_name = $_FILES[‘attachment’][‘name’];
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, “rb”); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
//Let’s start our headers
$headers = “From: $from_name<” . $_POST[‘from_email’] . “>n”;
$headers .= “Reply-To: <” . $_POST[‘from_email’] . “>n”;
$headers .= “MIME-Version: 1.0n”;
$headers .= “Content-Type: multipart/related; type=”multipart/alternative”; boundary=”—-=MIME_BOUNDRY_main_message”n”;
$headers .= “X-Sender: $from_name<” . $_POST[‘from_email’] . “>n”;
$headers .= “X-Mailer: PHP4n”;
$headers .= “X-Priority: 3n”; //1 = Urgent, 3 = Normal
$headers .= “Return-Path: <” . $_POST[‘from_email’] . “>n”;
$headers .= “This is a multi-part message in MIME format.n”;
$headers .= “——=MIME_BOUNDRY_main_message n”;
$headers .= “Content-Type: multipart/alternative; boundary=”—-=MIME_BOUNDRY_message_parts”n”;
$message = “——=MIME_BOUNDRY_message_partsn”;
$message .= “Content-Type: text/plain; charset=”iso-8859-1″n”;
$message .= “Content-Transfer-Encoding: quoted-printablen”;
$message .= “n”;
/* Add our message, in this case it’s plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= “$bodyn”;
$message .= “n”;
$message .= “——=MIME_BOUNDRY_message_parts–n”;
$message .= “n”;
$message .= “——=MIME_BOUNDRY_main_messagen”;
$message .= “Content-Type: application/octet-stream;ntname=”” . $attachment_name . “”n”;
$message .= “Content-Transfer-Encoding: base64n”;
$message .= “Content-Disposition: attachment;ntfilename=”” . $attachment_name . “”nn”;
$message .= $data; //The base64 encoded message
$message .= “n”;
$message .= “——=MIME_BOUNDRY_main_message–n”;
// send the message
mail(“[email protected]”, $subject, $message, $headers);
print “Mail sent. Thank you for using the MyNewName5333 Mailer.”;
}
?>
<!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” xml:lang=”en” lang=”en”>
<head>
</head>
<body>
<?php
switch ($action) {
case “send”:
sendMail();
showForm();
break;
default:
showForm();
}
?>
</body>
</html>
// check for valid file types
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<&lt Go Back');
}
}
}
[code=php]// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<< Go Back');
}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}[/code]
[CODE] if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
[/CODE]
[code=php]<?php
/* Mailer with Attachments */
$action = "";
$action = $_REQUEST['action'];
global $action;
function showForm() {
?>
<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<p>Name: <input name="from_name" size="40" /></p>
<p>Email: <input name="from_email" size="40" /></p>
<p>Subject: <input name="subject" size="40" /></p>
<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>
<p>Attachment: <input type="file" name="attachment" size="30" /></p>
<p><input type="submit" value="Send Your CV" /></p>
<?php
}
function sendMail() {
$from_name = stripslashes($_POST['from_name']);
$subject = stripslashes($_POST['subject']);
$body = stripslashes($_POST['body']);
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<< Go Back');
}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}
//Let's start our headers
$headers = "From: $from_name<" . $_POST['from_email'] . ">n";
$headers .= "Reply-To: <" . $_POST['from_email'] . ">n";
$headers .= "MIME-Version: 1.0n";
$headers .= "Content-Type: multipart/related; type="multipart/alternative"; boundary="----=MIME_BOUNDRY_main_message"n";
$headers .= "X-Sender: $from_name<" . $_POST['from_email'] . ">n";
$headers .= "X-Mailer: PHP4n";
$headers .= "X-Priority: 3n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_email'] . ">n";
$headers .= "This is a multi-part message in MIME format.n";
$headers .= "------=MIME_BOUNDRY_main_message n";
$headers .= "Content-Type: multipart/alternative; boundary="----=MIME_BOUNDRY_message_parts"n";
$message = "------=MIME_BOUNDRY_message_partsn";
$message .= "Content-Type: text/plain; charset="iso-8859-1"n";
$message .= "Content-Transfer-Encoding: quoted-printablen";
$message .= "n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "$bodyn";
$message .= "n";
$message .= "------=MIME_BOUNDRY_message_parts--n";
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_messagen";
$message .= "Content-Type: application/octet-stream;ntname="" . $attachment_name . ""n";
$message .= "Content-Transfer-Encoding: base64n";
$message .= "Content-Disposition: attachment;ntfilename="" . $attachment_name . ""nn";
$message .= $data; //The base64 encoded message
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_message--n";
// send the message
mail("[email protected]", $subject, $message, $headers);
header("Location: http://www.primarycarecommunity.net/success");
}
?>
[/code]
[code=php]<div id="right">
<?php
switch ($action) {
case "send":
sendMail();
showForm();
break;
default:
showForm();
}
?>
</div>[/code]
function showForm() {
?>
<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<p>Name: <input name="from_name" size="40" /></p>
<p>Email: <input name="from_email" size="40" /></p>
<p>Subject: <input name="subject" size="40" /></p>
<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>
<p>Attachment: <input type="file" name="attachment" size="30" /></p>
<p><input type="submit" value="Send Your CV" /></p>
<?php
}
[/quote]
<i>
</i>function showForm() {
echo '<form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<p>Name: <input name="from_name" size="40" /></p>
<p>Email: <input name="from_email" size="40" /></p>
<p>Subject: <input name="subject" size="40" /></p>
<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>
<p>Attachment: <input type="file" name="attachment" size="30" /></p>
<p><input type="submit" value="Send Your CV" /></p>';
}
Nope, same host. The test form is still live, here:http://www.primarycarecommunity.net/formtest.php - this one works
and my slightly modified and wp integrated form is here:
http://www.primarycarecommunity.net/vacancies - this one doesnt
That tutorial looks great and I may give it a go tonight to build the form again, but it doesn't show how to add the file upload box? Do I just copy that bit of code from my own?
Adrian[/QUOTE]
Nope no error messages, it displays just as it should, it just doesnt work, the code originally told it to display a thanks message, I changed it to redirect to a page, but when "send" is clicked, it redirects to index.html (it should redirect to success.php) and I dont get any email from it.[/QUOTE]
<form enctype="multipart/form-data" name="send" method="post" action="/index.php">
<input type="hidden" name="action" value="send">
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<p>Name: <input name="from_name" size="40"></p>
<p>Email: <input name="from_email" size="40"></p>
<p>Subject: <input name="subject" size="40"></p>
<p>Message: <textarea name="body" rows="5" cols="31"></textarea></p>
<p>Attachment: <input type="file" name="attachment" size="30"></p>
<p><input type="submit" value="Send Your CV"></p></form>
[/quote]
Well I sort of copied the redirect line of code from an old contact form processfile so not even sure if I had done that right, I will change the code back to the original which said:
// send the message
mail("[email protected] ", $subject, $message, $headers);
print "Mail sent. Thank you for using the Mailer.";
}[/QUOTE]
[code=php]
$worked = mail($var,$var,$var,$var);
if(!$worked){
//an error occurred and the mail was not sent
} else {
echo "Mail was sent successfully";
}
[/code]
[code=php]
$worked = mail("[email protected]", $subject, $message, $headers);
if(!$worked){
//an error occurred and the mail was not sent
echo "called: mail("[email protected]", $subject, $message, $headers)<br />";
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
} else {
echo "Mail was sent successfully";
}
[/code]
<i>
</i>echo "called: mail("[email protected]", $subject, $message, $headers)<br />";
action="/index.php"
[/quote]
I cant seem to find that at all?
Is that this bit...
echo '<form enctype="multipart/form-data" name="send" method="post" action="'.$_SERVER['PHP_SELF'].'">
were '.$_SERVER['PHP_SELF'].' is being replaced by /index.php do you think?[/QUOTE]
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
$message = "------=MIME_BOUNDRY_message_partsn";
$message .= "Content-Type: text/plain; charset="iso-8859-1"n";
$message .= "Content-Transfer-Encoding: quoted-printablen";
$message .= "n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "$bodyn";
$message .= "n";
$message .= "------=MIME_BOUNDRY_message_parts--n";
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_messagen";
$message .= "Content-Type: application/octet-stream;ntname="" . $attachment_name . ""n";
$message .= "Content-Transfer-Encoding: base64n";
$message .= "Content-Disposition: attachment;ntfilename="" . $attachment_name . ""nn";
$message .= $data; //The base64 encoded message
$message .= "n";
$message .= "------=MIME_BOUNDRY_main_message--n";
// send the message
mail("[email protected]", $subject, $message, $headers);
print "Mail sent. Thank you for using the Mailer.";
<i>
</i>echo '<form enctype="multipart/form-data" name="send" method="post">
ok i changed that line to:
header("Location:http://primarycarecommunity.net/success "); and i got:
Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:112) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106[/QUOTE]
[code=php] // send the message
mail("[email protected]", $subject, $message, $headers);
header("Location: http://primarycarecommunity.net/success");
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>[/code]
I still get:
Warning: Cannot modify header information - headers already sent by (output started at /home/adejones/public_html/wp-content/themes/pcc/jobs.php:113) in /home/adejones/public_html/wp-content/themes/pcc/jobs.php on line 106
but this time, it stopped the rest of the site loading from that point on i think because only my header image loaded.
notice this time it says :113 rather than :112 which is still <html <?php language_attributes(); ?>> because the exit(); pushed it down a line.[/QUOTE]
[code=php]// check for valid file types
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<< Go Back');
}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}
[/code]
last problem, i promise...
on validation, if the wrong file type is attached, the message appears to say so, but then anything under that doesnt load. I think the die command stops the rest of the page loading.
Can I get this to redirect to an error page?
If so, how do I amend this bit of code...
thanks
[code=php]// check for valid file types
[/QUOTE]
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$allowedExtensions = array("doc","docx","txt");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!
'.
''.
'<< Go Back');
}else{
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
}
}
}
[/code]
OK here's my walkthrough
if its a .doc, .docx or .txt I want the form submitted, I get an e-mail with the attached file and the user redirected to a success page, this does happen now and is great.
If it is not one of those file types, I want the user directed to an error page stating its an invalid file type with a back button to go back and resubmit the form,
OR
a dialog to pop up stating its an invalid file type, they click ok, and they can then select another file.
Whichever is easier to do.[/QUOTE]
<i>
</i>if(isInvalidType()){
Stuff was wrong with it, lets spit out some content and then "exit"
} else {
continue on as planned, nothing to see here
}
<i>
</i>if(isInvalidType()){
Stuff was wrong with it, lets spit out some javascript or a "warning" inline
and then continue to display the form from before
we will need to check if values were submitted so we can put them
into the form before it gets sent
} else {
continue on as planned, nothing to see here
}
OK lets go with option B, could you help me implement this?
I do really appreciate your help, you have been a life saver.[/QUOTE]
[code=php]
/* This stuff should be with your other stuff that validates the submission */
function isInvalidType($file){
$acceptedTypes = array('doc','txt'); //add more as needed
$mime = mime_content_type($file['name']);
if(in_array($mime,$acceptedTypes)){
return false; // this means the mime returned in one of our acceptable ones
} else {
return true; // this means the mime returned was not in our list
}
}
if(!function_exists('mime_content_type')) {
function mime_content_type($filename) {
/* You might need to add the docx, etc variants that MS office now uses */
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = strtolower(array_pop(explode('.',$filename)));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
elseif (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
else {
return 'application/octet-stream';
}
}
}
$formMsg = '';
/* don't forget to change your nameOfField to whatever you are using in your form */
if(isInvalidType($_FILES['nameOfField'])){
//Stuff was wrong with it, lets spit out some javascript or a "warning" inline
//and then continue to display the form from before
//we will need to check if values were submitted so we can put them
//into the form before it gets sent
$formMsg = 'this is the error message that you see';
} else {
//this is were the "working" code goes
// continue on as planned, nothing to see here
}
[/code]
[code=php]
//this goes where you are echoing the form
//each form element will need to be populated:
?> <input type="text" name="formElement"<?php if(isset($_POST['formElement'])){
echo " value="".$_POST['formElement'].""
}?> />
<?php
//this goes where you want any messages to be displayed
if(isset($formMsg) && !empty($formMsg)){
echo $formMsg;
}
[/code]
0.1.9 — BETA 5.19