PDA

View Full Version : complicated mail/subscription form



chechu
01-03-2010, 03:13 PM
Hey all,

First of all I hope for 2010 that DynamicDrive will continue helping out webdesigners all over, as it has been doing for several years. This forum is proof that kindness in the world still exists. Thanks for the past years, and I wish you many years to come.

I have started a site where I need some information (text and images with descriptions) from the people that wish to subscribe, so I am looking for a decent subscription mailform. I need the subscriber to fill in the following:

- name, adress, telephone, city, email (mandatory)
- websites or links to social websites (if possible a link with "add one", and then a new field comes up, 1 is mandatory)
- upload maximum 10 images with short text description (if possible a link with "add one", and then a new field comes up, image maximum 400 pixels high, 5 images mandatory)
- upload a Word or pdf document (mandatory)

It is very important that it is easy for me to see what description goes with what image.

Can anyone help me out with this, please ?
Thanks !

chechu
01-04-2010, 11:58 AM
I found the following code for attaching images and files:


<?php
$fileatt = ""; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = ""; // Filename that will be used for the file as the attachment

$email_from = ""; // Who the email is from
$email_subject = ""; // The Subject of the email
$email_txt = ""; // Message that the email has in it

$email_to = ""; // Who the email is too

$headers = "From: ".$email_from;

$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";

$data = chunk_split(base64_encode($data));

$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

$ok = @mail($email_to, $email_subject, $email_message, $headers);

if($ok) {
echo "<font face=verdana size=2>The file was successfully sent!</font>";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>


How can I mix that with the above explained requirements, please ?

MJH
01-04-2010, 01:53 PM
See:

http://www.freewarefiles.com/Plug-n-Play-Contact-Us-Form_program_53638.html

chechu
01-04-2010, 03:13 PM
Thanks for your input, MJH, but what you suggest does not upload files.
Any other suggestions, please ?

MJH
01-04-2010, 06:51 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Upload Images </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

var maxImages = 5;

/* **** Do not edit below this line **** */

/* Dynamic Image File Upload Form */
/* Copyright 2010, Michael J. Hill. Used with permission. www.javascript-demos.com */
/* Free use of the code, so long as both copyright notices are kept intact */

var root = "";
var nInput = "";
var IE = navigator.appName == "Microsoft Internet Explorer" ? true : false;

function insertInput(){

if (nInput.length > Number(maxImages)+Number(2))
{
alert('Maximum '+maxImages + ' images');
return false;
}
var nextUpload = document.createElement('input');
nextUpload.type = "file";
nextUpload.name = "userImg[]";
nextUpload.size = "25";
nextUpload.className = 'fInput';
nextUpload.onchange = function(){buildList()}
var lastUpload = root.getElementsByTagName('input');
lastUpload = lastUpload[lastUpload.length-3];
root.insertBefore(nextUpload,lastUpload);
}

function removeInput(){

if (nInput.length > 4)
{
root.removeChild(nInput[nInput.length-4]);
}
buildList();
}

function buildList(){

var nContainer = document.getElementById('nameList');
while (nContainer.lastChild)
{
nContainer.removeChild(nContainer.lastChild);
}
var listCollection = [];
for (i=0; i<nInput.length; i++)
{
if (nInput[i].type == "file")
{
var fullName = nInput[i].value;
var fileName = fullName.match(/[^\/\\]+$/);
var splitName = fullName.split(".");
var fileType = splitName[splitName.length-1];
if (!fileType){return false}
fileType = fileType.toLowerCase();
if (fileType == 'jpg' || fileType == 'jpeg' || fileType == 'gif')
{
listCollection[i] = fileName;
}
else {
alert('Invalid file type\nMust be jpg, jpeg or gif');
}
}
}
for (i=0; i<listCollection.length; i++)
{
var newItem = document.createElement('li');
newItem.appendChild(document.createTextNode(i+1+'- '+listCollection[i]));
nContainer.appendChild(newItem);
}
var nBox = document.getElementById('listBox');
if (nBox.scrollHeight > 0)
{
nBox.scrollTop = nBox.scrollHeight;
}
}

function validate(currForm){

var fileName = "";
var nForm = currForm.getElementsByTagName('input');
for (i=0; i<nForm.length; i++)
{
if (nForm[i].name = "userImg" && nForm[i].value == "")
{
alert('Complete all fields');
return false;
}
fileName = nForm[i].value.match(/[^\/\\]+$/);
fileName = fileName[0].split(".");
fileName[1] = fileName[1].toLowerCase();
if (/[^\w ]/.test(fileName[0]) || fileName.length > 2)
{
alert('A file name must not contain any special characters\nlike an apostrophe, period or hyphen');
return false;
}
if (fileName[1] != 'jpg' && fileName[1] != 'jpeg' && fileName[1] != 'gif')
{
alert('One or more of the selections\n is an invalid file type');
return false;
}
}
return true;
}

function init(){

root = document.getElementsByTagName('fieldset')[0];
nInput = root.getElementsByTagName('input');
var nForm = document.forms['img_upload'];
nForm.onsubmit = function()
{
return validate(this);
}
nForm['userImg[]'].onchange = function()
{
buildList();
}
nForm['next'].onclick = function()
{
insertInput();
}
nForm['remove'].onclick = function()
{
removeInput();
}
}

IE ? attachEvent('onload', init, false) : addEventListener('load', init, false);

</script>
<style type="text/css">

body
{
margin-top: 60px;
background-color: #eae3c6;
}

.headline
{
width: 170px;
margin-left: auto;
margin-right: auto;
margin-bottom: 5px;
}

form
{
margin-top: 0px;
padding: 0px;
}

fieldset
{
width: 279px;
margin-left: auto;
margin-right: auto;
padding: 0px;
background-color: #f0fff0;
border: 1px solid #87ceeb;
}

legend
{
font-family: helvetica;
font-size: 10pt;
font-weight: bold;
color: #00008b;
background-color: #87ceeb;
padding-left: 3px;
padding-right: 3px;
margin-bottom: 5px;
}

ul
{
margin-top: 2px;
}

.blank
{
display: none;
}

.list_container
{
display: block;
margin: auto;
border: 1px solid #87ceeb;
font-family: tahoma;
font-size: 10pt;
color: #00008b;
width: 273px;
height: 100px;
overflow: auto;
background-color: #ffffe0;
padding: 2px;
}

.review_msg
{
width: 123px;
margin-left: auto;
margin-right: auto;
}

.fInput
{
font-family: times;
font-size: 10pt;
margin-bottom: 3px;
margin-left: 16px;
}

.nextBtn
{
width: 75px;
font-family: veranda;
font-size: 9pt;
font-weight: bold;
margin-left: 21px;
margin-top: 5px;
margin-bottom: 8px;
background-color: #fff8dc;
border: solid 1px black;
letter-spacing: 1px;
}

.submitBtn
{
width: 75px;
font-family: veranda;
font-size: 9pt;
font-weight: bold;
margin-top: 5px;
margin-bottom: 8px;
background-color: #fff8dc;
border: solid 1px black;
letter-spacing: 1px;
}

.removeBtn
{
width: 75px;
font-family: veranda;
font-size: 9pt;
font-weight: bold;
margin-top: 5px;
margin-bottom: 8px;
background-color: #fff8dc;
border: solid 1px black;
letter-spacing: 1px;
}

.copyright_MJH
{
width: 92%;
margin-left: auto;
margin-right: auto;
margin-top: 35px;
background-color: transparent;
text-align: center;
font-family: veranda;
font-size: 8pt;
color: #d3d3d3;
}

.copyright_MJH a
{
color: #b0e0e6;
text-decoration: none;
}

</style>
</head>
<body>
<h3 class="headline"> Upload Your Images </h3>

<div id="listBox" class="list_container">
<div class="review_msg">Review Your Choices</div>
<ul id="nameList"><li class="blank"></li></ul>
</div>

<form name="img_upload" method="post" action="" enctype="multipart/form-data">
<fieldset>
<legend> Image Upload </legend>
<input type="file" name="userImg[]" size="25" class="fInput">
<input type="button" name="next" value="Next" class="nextBtn">
<input type="submit" name="submit" value="Submit" class="submitBtn">
<input type="button" name="remove" value="Remove" class="removeBtn">
</fieldset>
</form>

<!-- This copyright notice must be included in the document where the code is used -->
<div class="copyright_MJH">
Dynamic Image File Upload Form, Copyright &copy; 2010 Michael J. Hill
<a href="http://www.javascript-demos.com">JavaScript Demos</a>
All rights reserved. Used with permission.
</div>
<!-- This copyright notice must be included in the document where the code is used -->
</body>
</html>

chechu
01-04-2010, 06:59 PM
Wow, amazingly nice ! Thanks ! But where is it sent to ?
And how can I add the other features, please ?

chechu
01-07-2010, 01:49 PM
Seems like the ideal mailform would be too complicated.
How can I make the following, using the script MJH placed above:

- name, adress, telephone, city, email (mandatory)
- upload options like code above (new posibility to uplaod appears after uploading an attachment). The attachments should be images, Word or Pdf.

Can anyone help me out here, please ?

djr33
01-07-2010, 05:11 PM
Nothing in that is very complex, but the whole form becomes complex with all of the components. You will probably not be able to find one premade that does what you need, so you should find examples or (better) tutorials that do each component.
The first step is done with Javascript, adding attachments. The lazy way would be to allow up to 5 attachments and just have 5 inputs sitting there. If you must do this dynamically, things get more complex. However, you can do it either by adding them in an array <input type="file" name="filesarray[]">. Then each file will be the next entry in the array. I can't remember exactly what it is then available as, but you can just do print_r($_POST) and print_r($_FILES) to find out what is available. You could also just try to number the fields sequentially in Javascript then do a loop in PHP looking for file1, file2, ... fileN.

After that it becomes a much more normal form.

In the PHP you must handle several things:
1. the files must be saved, etc. (based on the method above)
2. required fields must be validated. This is very easy: if (something is wrong) { $error = 'your message here'; }
Then at the end of the validation part, just check: if (!isset($error)) { //process form
else { //repeat the form, and echo $error }
3. One problem here is that validation means you may send the user back to the form. If you do this, then the file will be lost. They must then search for and select the file again, then upload it again. This is very annoying. You could try to store it in a temporary folder on the server, but keeping track of that would be a small project in itself.

One possibly simpler approach would be to have a series of successive pages each with one step: 1) form; 2) upload file; 3) confirmation page with final "submit" button and "or upload another file" [=> (p.2)].

chechu
01-07-2010, 05:53 PM
I like the idea of several pages, but have no idea how the coding would really look like.

This is the code that I use now for my mail form:

<?php
if ($_POST["action"] == "send"){
if ($_POST[naam] != " je naam" and $_POST[naam] != "" and $_POST[email] != " je e-mail adres" and $_POST[email] != "" and $_POST[bericht] != "") {
mail ("name@mail.be", "bericht",
"
Naam: ".$_POST['naam']."
E-mail: ".$_POST['email']."
Bericht: ".$_POST['bericht']."
",

"From: ".$_POST['naam']." <".$_POST['email'].">");

$subject = "bevestiging bericht via portretkunst.be";
$msg = "

Dit is een automatisch verzonden mail. Gelieve niet te antwoorden.
";

mail($_POST[email], $subject, $msg);

echo '<br><img src="images/sent.gif" style="border:0px;height:12px;width:12px;padding-right:10px;">Dankjewel.<br><br>Je bericht is verzonden, <br>en je zal een bevestiging ontvangen.';

}

else{
echo '<br><img src="images/clear.gif" style="border:0px;height:12px;width:12px;padding-right:10px;">Gelieve alle velden in te vullen.<br><br>Je naam, email adres en bericht<br> zijn verplichte velden.<br><br><a href="about.php"><font color="#565656;">[graag opnieuw]</font></a>';
}
}
?>

How would I combine that with the above code of MJH, spreading it over two pages ? Then I will be a step further already!

djr33
01-07-2010, 06:37 PM
It seems like your code and the code above are basically doing the same thing. You would need two entirely different forms (one for the info and one for the files) that would work together only in that they are combined in storage.
Submit page 1 (info) and store that as a session variable (or, possibly, a hidden field, but that is somewhat messier). Then on that next page just upload a file and store it on the server and save the data. If they want to add another file, just go back to that same page and "attach" a new file to that data (probably by storing the filename/location on the server of where you uploaded it).
This is going to take a significant amount of time to do, so you might want to find someone who can do it for you (possibly for pay). At the moment I'm too busy to put a whole system together.
As I said above, the components are fairly simple, but keeping track of all of the data and organizing it in the end may be somewhat difficult.

chechu
01-07-2010, 06:41 PM
But in fact, nothing needs to be stored ? Even if both codes would be mixed on one page, one form, that would be fine.

So just a few fields to fill in (as my code above) and a few files to attach (like code MJH) in the same form, and I can start. My problem is that I do not know how to "mix" them ...

I need this urgently, that's why I can be flexible in the start-up form. After that, indeed I will contact a "professional" to have exactly what I need.

djr33
01-08-2010, 07:30 PM
The problem is what you need specifically: any number of attachments (dynamically) and form validation.

You submit the form, the files are stored (where?), then it validates, finds an error and sends you back to the original page. You could do this where you have a "stored" file, just by filename, with a link to "delete attachment", or you could add new attachments again, but this is complex and might be messy compared to what you want.

Even to figure out HOW to do this takes a bit of time, and then doing it would take someone fairly experienced with contact forms at least 2 hours to code (maybe a lot more depending on how many "extras" you need, like the dynamic javascript "add an attachment" option).

If you want the "quick and dirty" version, then just skip validating the form (just refuse incorrect data on the server, so no hacking attempts would work, then send them back to the original, empty form), and allow a specific number of attachments. Maybe one (easiest), or just a list of five attachments (and if they leave all but one blank then there won't be an error-- it just won't do those).

If you just want to add an attachment option to an existing form, that's a lot more reasonable, but probably still about an hour of work because an existing form has a specific setup that must be modified to add additional behavior.
This is something like taking a truck that has two seats and trying to add a third in the middle. It's possible, but to make it work well and be safe there's a lot that has to be done. And now if you want it customizable to any number of seats, that's another issue entirely, with its own complexities even just starting at "how can I do that?"

chechu
01-08-2010, 08:02 PM
Thanks for your explanation, Daniel.
I already have this: http://www.portretkunst.be/ZZZ.php, but I would like to have the option that MJH sent included (upload of multiple files posibility), or at least add ten upload fields.

This is the code I would start from:


<?php
// Your e-mail adress:
$mailto = "naam@sitenaam.nl";

# Maximum size of attachment in bytes:
$max_attach_size = 500000;

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Formmailer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body><?php
/*if (empty($_POST['form_submitted']))
{
?></font><p><font color="#FFFFFF">Please fill out the form:</font></p>
<font color="#FFFFFF"><?php
}
*/
if (isset($_POST["form_submitted"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$text = $_POST['text'];

unset($errors);
if ($email != "" and !preg_match("/^[^@]+@.+\.\D{2,5}$/", $email)) $errors[] = "e-mail address lijkt incorrect";
if ($text == "") $errors[] = "Geen bericht geplaatst";
if ($_FILES['probe']['size'] > $max_attach_size) $errors[] = "Bijlage is te groot(".number_format($_FILES['probe']['size']/1000,0,",","")." KB) - maximum size: ".number_format($max_attach_size/1000,0,",","")." KB";

if (empty($errors))
{
$text = stripslashes($text);
$subject = stripslashes($subject);
if ($name != "") $mail_name=$name; else $mail_name="Unknown";
if ($subject != "") $mail_subject = $subject; else $mail_subject = "No subject";
if ($email != "") $mail_email = $email; else $mail_email = "email@unknown.xyz";
$ip = $_SERVER["REMOTE_ADDR"];

// if attachment, MIME-Mail:
if (isset($_FILES['probe']['name']) && trim($_FILES['probe']['name']) != "")
{
// read and encode file:
$datei_content = fread(fopen($_FILES['probe']['tmp_name'],"r"),filesize($_FILES['probe']['tmp_name']));
$datei_content = chunk_split(base64_encode($datei_content),76,"\n");
// Boundary:
$boundary = md5(uniqid(rand()));
// Mail-Header:
$mail_header = "From: ".$mail_name." <".$mail_email.">\n";
$mail_header .= "X-Sender-IP: ".$ip."\n";
$mail_header .= "MIME-Version: 1.0\n";
$mail_header .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\n";
$mail_header .= "This is a multi-part message in MIME format.\n";
// Mail-Text:
$mail_header .= "--".$boundary;
$mail_header .= "\nContent-Type: text/plain";
$mail_header .= "\nContent-Transfer-Encoding: 8bit";
$mail_header .= "\n\n".$text;
// Attachment:
$mail_header .= "\n--".$boundary;
$mail_header .= "\nContent-Type: ".$_FILES['probe']['type']."; name=\"".$_FILES['probe']['name']."\"";
$mail_header .= "\nContent-Transfer-Encoding: base64";
$mail_header .= "\nContent-Disposition: attachment; filename=\"".$_FILES['probe']['name']."\"";
$mail_header .= "\n\n".$datei_content;
// End:
$mail_header .= "\n--".$boundary."--";
// Sende E-Mail und gebe Fehler bzw. Bestaetigung aus
if (@mail($mailto,$mail_subject,"",$mail_header)) $sent = true; else $errors[] = "no connection to the mailserver - please try again later";
}
// no attachment, normal E-mail:
else
{
$mail_header = "From: ".$mail_name." <".$mail_email.">\n";
$mail_header .= "X-Sender-IP: $ip\n";
$mail_header .= "Content-Type: text/plain";
if (@mail($mailto,$mail_subject,$text,$mail_header)) $sent = true; else $errors[] = "no connection to the mailserver - please try again later";
}

// copy to sender:
if (isset($sent) && isset($email) && $email != "" && isset($_POST['copy']))
{
if (isset($_FILES['probe']['name']) && trim($_FILES['probe']['name']) != "") $copy_mail_text = "Copy of the e-mail:\n\n".$text."\n\nAttachment: ".$_FILES['probe']['name']; else $copy_mail_text = "Copy of the e-mail:\n\n".$text;
$header= "From: ".$mailto."\n";
$header .= "X-Sender-IP: ".$ip."\n";
$header .= "Content-Type: text/plain";
@mail($email, $mail_subject, $copy_mail_text, $header);
}
}
}

if (empty($sent))
{
if(isset($errors))
{
?></font><p class="caution"><font color="#FFFFFF">Error:</font></p><ul>
<font color="#FFFFFF"><?php foreach($errors as $f) { ?></font><li>
<font color="#FFFFFF"><?php echo $f; ?></li><?php } ?></font></ul>
<font color="#FFFFFF"><br /><?php
}

?></font><form method="post" action="<?php echo basename($_SERVER["PHP_SELF"]); ?>" enctype="multipart/form-data"><div>
<p><font color="#FFFFFF"><span class="style2"><font face="Verdana" size="2">
Naam</font></span><font face="Verdana" size="2"><span class="style2">:</span><br />
</font>
</font><font color="#FFFFFF">
<input name="name" value="<?php if (isset($name)) echo htmlentities(stripslashes($name)); else echo ""; ?>" size="25" style="font-family: Verdana; border: 1px dashed #000000" />
<font face="Verdana" size="2">
<br />
<span class="style2">E-mail:</span><br />
</font>
</font><font color="#FFFFFF">
<input name="email" value="<?php if (isset($email)) echo htmlentities(stripslashes($email)); else echo ""; ?>" size="25" style="font-family: Verdana; border: 1px dashed #000000" />
<font face="Verdana" size="2">
<br />
<span class="style2">Onderwerp:</span><br />
</font>
</font><font color="#FFFFFF">
<input name="subject" value="<?php if (isset($subject)) echo htmlentities(stripslashes($subject)); else echo ""; ?>" size="25" style="font-family: Verdana; border: 1px dashed #000000" />
<font face="Verdana" size="2">
<br />
<span class="style2">Bericht:</span><br />
</font>
</font><font color="#FFFFFF">
<textarea name="text" cols="25" rows="7" style="font-family: Verdana; border: 1px dashed #000000"><?php if (isset($text)) echo htmlentities(stripslashes($text)); else echo ""; ?>
</textarea>
<font face="Verdana" size="2">
<br />
<span class="style2">Bijlagen:</span><br />
</font>
</font><font color="#FFFFFF">
<input type="file" name="probe" value="<?php if (isset($_POST['probe'])) echo htmlentities(stripslashes($_POST['probe'])); else echo ""; ?>" size="16" style="font-family: Verdana; border: 1px dashed #000000"/>
</font>
</p>
</p>
<p><font face="Verdana"><font color="#FFFFFF"><input type="checkbox" name="copy" value="true" /></font><font size="2" color="#FFFFFF">
<span class="style2">Kopietje naar jezelf sturen?</span> </font></font>
<font color="#FFFFFF">
<input type="submit" name="form_submitted" value="OK - Verzenden" style="font-family: Verdana; border: 1px dashed #000000" /></font><font face="Verdana" size="2" color="#FFFFFF">
</font> </p>
</div>
</form><font color="#FFFFFF"><?php
}
else
{
if (empty($email)) { ?></font></font><font color="#FFFFFF"> </font>
<p><font color="#FFFFFF"><b><font face="Verdana" size="1">Bedankt</font></b><font size="1" face="Verdana"><b>!</b><br />
Je mail is verzonden alleen kan ik je niet terug mailen omdat je geen e-mail
adres hebt ingevuld! </font></font></p>
<font face="Verdana" size="1"><font color="#FFFFFF"><?php }
else { ?></font></font><font color="#FFFFFF"> </font>
<p><font color="#FFFFFF"><b><font face="Verdana" size="1">Bedankt</font></b><font size="1" face="Verdana"><b>!</b><br />
Je bericht is met succes verzonden ik zal zo spoedig mogelijk terug mailen. </font>
</font></p>
<font face="Verdana" size="1" color="#FFFFFF"><?php }
}

?>

chechu
01-13-2010, 07:27 PM
Could anyone be able to add the two codes together, please ?
Thanks !

djr33
01-15-2010, 04:09 AM
I'm sorry that I don't really have time to take this on now. But you still need to explain what to do with the conflict between the file uploads and validation. Personally I would split it for better usability but that would not be easier coding.
"just merging" those would result in the user needing to reupload the files every time it did not validate. Is this acceptable?