PHPmailer integreren met formulier incl. uploadfunctie

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

Tim Rigter

Tim Rigter

08/04/2011 21:36:48
Quote Anchor link
Hallo,

ik heb een compleet werkend upload-formulier die helaas niet op mijn domein werkt.
Daarom ben ik nu bezig om PHP-mailer daarin te verwerken.

Mijn PHP-kennis is nog niet zo goed aangezien ik er pas een week of 2 mee bezig ben.

Toch wil ik heel graag dit contactformulier werkend op mijn site zien te krijgen.

Wie kan me wat goede tips geven? Ik moet ergens mijn variabelen aan de class phpmailer doorgeven, maar ik snap niet echt hoe.......

Dit is de index.php:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
//start session
session_start();

// Include all the output functions
require_once('fns.php');
require_once('class.phpmailer.php');


// populate input fields into the session using a sub-array
$_SESSION['myForm'] = $_POST;

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Upload Form</title>
<style type="text/css">
body {font-family: Helvetica, Arial, sans-serif; line-height: 135%; margin-left:50px;}
#uploadform {width: 350px;}
label {display: block;}
input, textarea {width: 90%;}
input#submit {width: auto;}
.required {color: red;}
#formfeedback {background: #fdfbab; padding: 5px;}
</style>
</head>
<body>

<h1>Upload Form</h1>
<div id="uploadform">
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
    // contact form
    if (isset($_POST['submitted']) && ('true' == $_POST['submitted'])) {
        // checks if the form is submitted and then processes it
        process_form();
        
    }
else {
        // else prints the form
        print_form();
    }


    
    ?>

</div>
</body>
</html>
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php session_destroy(); //unset session data ?>


En hier het formulier:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
<?php
//start session
session_start();

// prints form
function print_form(){
?>

<p><span class="required">*</span> Required fields</p>
<form action="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SERVER[PHP_SELF];?>
" method="post" enctype="multipart/form-data" id="uploadform">
<p><label for="namefrom">Name <span class="required">*</span></label>
<input name="namefrom" id="namefrom" type="text" class="field" value="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['namefrom']; ?>
" tabindex="1"/></p>

<p><label for="company">Company</label>
<input name="company" id="company" type="text" class="field" value="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['company']; ?>
" tabindex="2"/></p>

<p><label for="emailfrom">Email <span class="required">*</span></label>
<input name="emailfrom" id="emailfrom" type="text" class="field" value="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['emailfrom']; ?>
" tabindex="3"/></p>

<p><label for="phone">Phone</label>
<input name="phone" id="phone" type="text" class="field" value="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['phone']; ?>
" tabindex="4"/></p>

<p><label for="subject">Subject <span class="required">*</span></label>
<input name="subject" id="subject" type="text" class="field" value="
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['subject']; ?>
" tabindex="5"/></p>

<p><label for="comments">Comments <span class="required">*</span></label>
<textarea name="comments" id="comments" rows="7" cols="10" class="field" tabindex="6">
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
<?php echo $_SESSION['myForm']['comments']; ?>
</textarea></p>

<p><label for="attachment">File Upload<br />(1 file only, max file size 1024kb. Allowed file formats are .doc, .pdf, .zip, .rar)</label>
<input name="attachment" id="attachment" type="file" tabindex="7">

<p><input type="submit" name="submit" id="submit" value="Send Email!" tabindex="8"/></p>
<p><input type="hidden" name="submitted" value="true" /></p>
</form>
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
<?php
}

// enquiry form validation

function process_form() {
    // Read POST request params into global vars
    // FILL IN YOUR EMAIL

    $to = "[email protected]";
    $subject = trim($_POST['subject']);
    $namefrom = trim($_POST['namefrom']);
    $company = trim($_POST['company']);
    $phone = trim($_POST['phone']);
    $emailfrom = trim($_POST['emailfrom']);
    $comments = trim($_POST['comments']);
    
    // Allowed file types. add file extensions WITHOUT the dot.
    $allowtypes=array("zip", "rar", "doc", "pdf");
    
    // Require a file to be attached: false = Do not allow attachments true = allow only 1 file to be attached
    $requirefile="true";
    
    // Maximum file size for attachments in KB NOT Bytes for simplicity. MAKE SURE your php.ini can handel it,
    // post_max_size, upload_max_filesize, file_uploads, max_execution_time!
    // 2048kb = 2MB,       1024kb = 1MB,     512kb = 1/2MB etc..

    $max_file_size="1024";
    
    // Thank you message
    $thanksmessage="Your email has been sent, we will respond shortly.";

    $errors = array(); //Initialize error array

    //checks for a name

    if (empty($_POST['namefrom']) ) {
        $errors[]='You forgot to enter your name';
        }


    //checks for an email
    if (empty($_POST['emailfrom']) ) {
        $errors[]='You forgot to enter your email';
        }
else {

        if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['emailfrom'])))) {
            $errors[]='Please enter a valid email address';
        }
// if eregi
    } // if empty email

    //checks for a subject

    if (empty($_POST['subject']) ) {
        $errors[]='You forgot to enter a subject';
        }


    //checks for a message
    if (empty($_POST['comments']) ) {
        $errors[]='You forgot to enter your comments';
        }

        
     // checks for required file
    // http://amiworks.co.in/talk/handling-file-uploads-in-php/

    if($requirefile=="true") {
        if($_FILES['attachment']['error']==4) {
            $errors[]='You forgot to attach a file';
        }
    }

        
    //checks attachment file
    // checks that we have a file

    if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) {
            // basename -- Returns filename component of path
            $filename = basename($_FILES['attachment']['name']);
            $ext = substr($filename, strrpos($filename, '.') + 1);
            $filesize=$_FILES['attachment']['size'];
            $max_bytes=$max_file_size*1024;
            
            //Check if the file type uploaded is a valid file type.
            if (!in_array($ext, $allowtypes)) {
                $errors[]="Invalid extension for your file: <strong>".$filename."</strong>";
                
        // check the size of each file
        } elseif($filesize > $max_bytes) {
                $errors[]= "Your file: <strong>".$filename."</strong> is to big. Max file size is ".$max_file_size."kb.";
            }
            
    }
// if !empty FILES

    if (empty($errors)) { //If everything is OK
        
        // send an email
        // Obtain file upload vars

        $fileatt      = $_FILES['attachment']['tmp_name'];
        $fileatt_type = $_FILES['attachment']['type'];
        $fileatt_name = $_FILES['attachment']['name'];
        
        // Headers
        $headers = "From: $emailfrom";
        
        // create a boundary string. It must be unique
          $semi_rand = md5(time());
          $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

          // Add the headers for a file attachment
          $headers .= "\nMIME-Version: 1.0\n" .
                      "Content-Type: multipart/mixed;\n" .
                      " boundary=\"{$mime_boundary}\"";

          // Add a multipart boundary above the plain message
          $message ="This is a multi-part message in MIME format.\n\n";
          $message.="--{$mime_boundary}\n";
          $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
          $message.="Content-Transfer-Encoding: 7bit\n\n";
          $message.="From: ".$namefrom."\n";
          $message.="Company: ".$company."\n";
          $message.="Phone: ".$phone."\n";
          $message.="Comments: ".$comments."\n\n";
        
        if (is_uploaded_file($fileatt)) {
          // Read the file to be attached ('rb' = read binary)
          $file = fopen($fileatt,'rb');
          $data = fread($file,filesize($fileatt));
          fclose($file);

          // Base64 encode the file data
          $data = chunk_split(base64_encode($data));

          // Add file attachment to the message
          $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";
        }

        
        
        // Send the completed message
        
        $envs = array("HTTP_USER_AGENT", "REMOTE_ADDR", "REMOTE_HOST");
        foreach ($envs as $env)
        $message .= "$env: $_SERVER[$env]\n";

$mail             = new PHPMailer();

$body             = file_get_contents('contents.html');
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "smtp.mijnhostingpartner.nl"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only

$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "smtp.mijnhostingpartner.nl"; // sets the SMTP server
$mail->Port       = 26;                    // set the SMTP port for the GMAIL server
$mail->Username   = "[email protected]"; // SMTP account username
$mail->Password   = "****";        // SMTP account password
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddReplyTo("[email protected]","First Last");

//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($body);

$address = "[email protected]";
$mail->AddAddress($address, "John Doe");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
  echo "Message sent!";
}


        
        if(!mail($to,$subject,$message,$headers)) {
            exit("Mail could not be sent. Sorry! An error has occurred, please report this to the website administrator.\n");
        }

        else {
            echo '<div id="formfeedback"><h3>Thank You!</h3><p>'. $thanksmessage .'</p></div>';
            unset($_SESSION['myForm']);
            print_form();
            
        }
// end of if !mail
        
    } else { //report the errors
        echo '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
        foreach ($errors as $msg) { //prints each error
                echo " - $msg<br />\n";
            }
// end of foreach
        echo '</p><p>Please try again</p></div>';
        print_form();
    }
//end of if(empty($errors))

} // end of process_form()


?>


Toevoeging op 08/04/2011 22:38:28:

had trouwens wel bij 'Beginnen met PHP' moeten staan bedenk ik me nu :D
Gewijzigd op 08/04/2011 23:04:57 door Tim Rigter
 
PHP hulp

PHP hulp

22/12/2024 20:57:39
 
Aad B

Aad B

08/04/2011 22:59:42
Quote Anchor link
// Include all the output functions
require_once('/fns.php');
require_once('/class.phpmailer.php');
Je includes zijn niet goed. Includen van / zal niet werken.
Laat de slash weg of maak er ./ van.
Er zijn prima beschijvingen voor php mailer te vinden op het net.
Regel 175 zou je mail moeten verzenden!
De if structuur beginnend op regel 182 is de oude manier en moet weg.
Gewijzigd op 08/04/2011 23:02:09 door Aad B
 
Tim Rigter

Tim Rigter

08/04/2011 23:04:07
Quote Anchor link
:s klopt, die had ik al aangepast. maar verkeerde index hierbij gezet.

Maar ik loop nu al een paar dagen google door te spitten, en iedereen zegt dat het heel gemakkelijk is om phpmailer in je script te zetten, maar er is naar mijn idee geen goed voorbeeld te vinden.........

Maar vanaf 182 tot aan het einde kan dus alles weg, en daar moet dan de phpmailer dus? ga ik dat eens proberen

Toevoeging op 08/04/2011 23:30:58:

Nou, ik ben een stap verder. Maar als ik nu mijn formulier invul krijg ik alleen de testmail van phpmailer binnen, zonder de informatie die uit het formulier komt.

Ook krijg ik keurig een foutmelding als ik een veld niet invoer (zonder dat er iets gemailt wordt)

Hoe krijg ik de juiste informatie in mijn mail?

heb hier het script even verwijderd omdat het anders zo'n lang verhaal wordt

Toevoeging op 09/04/2011 12:43:01:

Nu heb ik het volgende (vanaf regel 137)
Maar ik krijg nu wel een mail binnen met alle waarden, maar met een fout in de bijlage, en de mail is totaal niet opgemaakt.

Wat doe ik nou nog fout?



Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
// Send the completed message
        
        $envs = array("HTTP_USER_AGENT", "REMOTE_ADDR", "REMOTE_HOST");
        foreach ($envs as $env)
        $message .= "$env: $_SERVER[$env]\n";

$mail             = new PHPMailer();
$mail->IsHTML(true);
$body             = $message;
$body             = eregi_replace("[\]",'',$body);

$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "smtp.mijnhostingpartner.nl"; // SMTP server
$mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
                                           // 1 = errors and messages
                                           // 2 = messages only

$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Host       = "smtp.mijnhostingpartner.nl"; // sets the SMTP server
$mail->Port       = 26;                    // set the SMTP port for the server
$mail->Username   = "[email protected]"; // SMTP account username
$mail->Password   = "***";        // SMTP account password
$mail->SetFrom('[email protected]', 'Tim Rigter');
$mail->AddReplyTo("[email protected]","Tim Rigter");

//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

//$mail->Subject    = "PHPMailer Test Subject via smtp, basic with authentication";

$mail->Subject = $subject;
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

$mail->MsgHTML($message);

$address = "[email protected]";
$mail->AddAddress($address, "Tim");

$mail->AddAttachment("images/phpmailer.gif");      // attachment
$mail->AddAttachment($fileatt); // attachment


if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
  echo '<div id="formfeedback"><h3>Thank You!</h3><p>'. $thanksmessage .'</p></div>';
            unset($_SESSION['myForm']);
            print_form();
}
}
else { //report the errors
        echo '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
        foreach ($errors as $msg) { //prints each error
                echo " - $msg<br />\n";
            }
// end of foreach
        echo '</p><p>Please try again</p></div>';
        print_form();
    }
//end of if(empty($errors))

} // end of process_form()

?>
Gewijzigd op 09/04/2011 12:44:14 door Tim Rigter
 



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.