Adattare script di "form mail con upload file" al mio form mail HTML!

Manuel Melluso

Nuovo Utente
31 Gen 2013
17
0
0
40
Buongiorno ragazzi,

da quasi un mese a questa parte la mia cartella "download" è piena zeppa di script e plugin per form mail con funzione di invio allegato...ne funzionasse uno!! Uno manda solo la mail, l'altro solo l'allegato, un'altro manda mail vuote, un'altro manda geroglifici...non ce la faccio più! :crying:

Ora ho questo che sembra funzioni bene, sono 2 file, lo script PHP e la pagina PHP con il form; ora devo solo adattare lo script PHP al mio form HTML. Qualcuno sarebbe così gentile da aiutarmi tenendo presente che non conosco il PHP?!

Lo script PHP
PHP:
<?php
//start session
session_start();

/**
 * Contact form with file attachment
 * Release Date: April 24th 2008
 * Author: Elle Meredith <http://designbyelle.com.au/>
 * 
 * Resources used to create this script
 * phMailer <http://www.phphq.net?script=phMailer> by Scott L. <[email protected]>
 * an article on Sitepoint by Kevin Yank, (13 Feb 2003) Accessed on April 24, 2008
 * "Advanced email in PHP" <http://www.sitepoint.com/article/advanced-email-php>
 * and "PHP: Sending Email (Text/HTML/Attachments)"
 * <http://www.webcheatsheet.com/php/send_email_text_html_attachment.php>
 *
 * one more: http://www.sebastiansulinski.co.uk/web_design_tutorials/php/php_file_upload.php
 *
 * This script is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This script is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * http://www.gnu.org/licenses/gpl.txt
 *
 */



// prints form
function print_form(){
?>
<p><span class="required">*</span> Required fields</p>
	<form method="post" action="<?php echo $_SERVER[’PHP_SELF’];?>" id="uploadform" enctype="multipart/form-data">
	<p><label for="namefrom">Name <span class="required">*</span></label>
	<input name="namefrom" id="namefrom" type="text" class="field" value="<?= $_SESSION['myForm']['namefrom']; ?>" tabindex="1"/></p>
	
	<p><label for="company">Company</label>
	<input name="company" id="company" type="text" class="field" value="<?= $_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="<?= $_SESSION['myForm']['emailfrom']; ?>" tabindex="3"/></p>
	
	<p><label for="phone">Phone</label>
	<input name="phone" id="phone" type="text" class="field" value="<?= $_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="<?= $_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"><?= $_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>
<?php
}

// enquiry form validation

function process_form() {
	// Read POST request params into global vars
	// FILL IN YOUR EMAIL
	$to = "mia_mail.it";
	$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","jpeg","jpg");
	
	// 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";
		
		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()
?>
La corrispettiva pagina PHP
PHP:
<?php
//start session
session_start();

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

// populate input fields into the session using a sub-array
// check http://www.scriptygoddess.com/archives/2007/05/28/how-to-use-session-cookies-in-php/
// also check the above link for remembering checkboxes values
$_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">
	<?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>
<?php session_destroy(); //unset session data ?>
Il mio form...devo ancora aggiungere il pulsante upload!
HTML:
<link href="stilee.css" rel="stylesheet" type="text/css" />

<form action="contactengine.php" method="post" enctype="multipart/form-data" name="contacts form" id="form_contatti">
    
	<input name="name" type="text" placeholder=" Write here your name" id="campo_nome"/>
    <input name="company" type="text" placeholder=" Write here your company" id="campo_company"/>
    <input name="email" type="text" placeholder=" Write here your email" id="campo_email"/>
    <span class="Stile10">
    <textarea name="text" placeholder=" Write here your request" id="campo_testo"></textarea>
    </span>
    <a><input type="submit" id="pulsante_invio" value="Send"/></a>
  
  </form>
Grazie in anticipo a chi volesse aiutarmi.
 

Manuel Melluso

Nuovo Utente
31 Gen 2013
17
0
0
40
Ciao helpdesk,

grazie per il tuo consiglio; durante la mia odissea ho già incontrato quel tutorial ma non mi ha aiutato! Vorrei riuscire ad adattare questo al mio semplicissimo form html. In realtà sul mio sito ho un form che già funziona al quale, però, non riesco a far funzionare la funzione "upload". Quando ci ho provato i file caricati non arrivavano!

Comunque scusa, lasciami fare questo ragionamento:

(sempre facendo riferimento ai file che ho postato) se ho ben capito tutta questa parte dello script a me non servirebbe visto che il form già c'è nella mia pagina html...giusto? Quindi potrei toglierla?! :book:

PHP:
<?php 
//start session 
session_start(); 

/** 
 * Contact form with file attachment 
 * Release Date: April 24th 2008 
 * Author: Elle Meredith <http://designbyelle.com.au/> 
 *  
 * Resources used to create this script 
 * phMailer <http://www.phphq.net?script=phMailer> by Scott L. <[email protected]> 
 * an article on Sitepoint by Kevin Yank, (13 Feb 2003) Accessed on April 24, 2008 
 * "Advanced email in PHP" <http://www.sitepoint.com/article/advanced-email-php> 
 * and "PHP: Sending Email (Text/HTML/Attachments)" 
 * <http://www.webcheatsheet.com/php/send_email_text_html_attachment.php> 
 * 
 * one more: http://www.sebastiansulinski.co.uk/web_design_tutorials/php/php_file_upload.php 
 * 
 * This script is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version. 
 *  
 * This script is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details. 
 * http://www.gnu.org/licenses/gpl.txt 
 * 
 */ 



// prints form 
function print_form(){ 
?> 
<p><span class="required">*</span> Required fields</p> 
    <form method="post" action="<?php echo $_SERVER[’PHP_SELF’];?>" id="uploadform" enctype="multipart/form-data"> 
    <p><label for="namefrom">Name <span class="required">*</span></label> 
    <input name="namefrom" id="namefrom" type="text" class="field" value="<?= $_SESSION['myForm']['namefrom']; ?>" tabindex="1"/></p> 
     
    <p><label for="company">Company</label> 
    <input name="company" id="company" type="text" class="field" value="<?= $_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="<?= $_SESSION['myForm']['emailfrom']; ?>" tabindex="3"/></p> 
     
    <p><label for="phone">Phone</label> 
    <input name="phone" id="phone" type="text" class="field" value="<?= $_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="<?= $_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"><?= $_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> 
<?php 
}
 

Manuel Melluso

Nuovo Utente
31 Gen 2013
17
0
0
40
ciao
dai un occhio alla classe phpmailer, ti semplifica la vita
https://www.mrw.it/php/articoli/inviare-email-classe-phpmailer_631.html
Ciao borgo italia,

grazie per il tuo intervento.

visto che ci sono ne approfitto per chiederti questa cosa che continuo a non capire:
PHP:
$messaggio->From='[email protected]';
$messaggio->AddAddress('[email protected]');
$messaggio->AddReplyTo('[email protected]');
Mi spiegheresti queste 3 voci e cosa dovrei inserire al posto di "[email protected]" e "[email protected]"?

Ti ricordo sempre che il mio form è questo
HTML:
<form action="contactengine.php" method="post" enctype="multipart/form-data" name="contacts form" id="form_contatti">
    
	<input name="name" type="text" placeholder=" Write here your name" id="campo_nome"/>
    <input name="company" type="text" placeholder=" Write here your company" id="campo_company"/>
    <input name="email" type="text" placeholder=" Write here your email" id="campo_email"/>
    <span class="Stile10">
    <textarea name="text" placeholder=" Write here your request" id="campo_testo"></textarea>
    </span>
    <a><input type="submit" id="pulsante_invio" value="Send"/></a>
  
  </form>
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
intanto una cosa: non tutti sono obbligatori es.
PHP:
$messaggio->IsHTML(true);
se messo così invia il messaggio in formato html (cioè con i tag html), ma puo essere omesso, allora invia in formato testo
poi veniamo a quelli che hai postato

PHP:
$messaggio->From='[email protected]';
indica da che arriva il messaggio, se nel form hai messo che l'utente indichi il suo indirizzo email devi mettere il suo indirizzo
es (metto brutalmente per farti capire)
PHP:
$messaggio->From="$_POST['indirizzo_email_mittente']";

PHP:
$messaggio->AddAddress('[email protected]');
richiede a chi deve essere inviato il messaggio, se es il form fa parte della classica pagina "contattami" deve contenere il tuo indirizzo (es)
PHP:
$messaggio->AddAddress('tuo_indirizzo@pinco_pallo.it');
se invece vuo far recapitare a qualcun altro devi mettere l'indirizzo di questo qualcunaltro

serve per usare il rispondi (se usi es autlook c'è l'opzione rispondi a...)
PHP:
$messaggio->AddReplyTo('[email protected]');
ti indica a chi eventualmente deve essere inviata la risposta, generalmente è l'indirizzo en+mali del mittente

spero di essere stato chiaro
 

Manuel Melluso

Nuovo Utente
31 Gen 2013
17
0
0
40
mmm...vediamo un pò...quindi nel mio caso
HTML:
<form action="contactengine.php" method="post" enctype="multipart/form-data" name="contacts form" id="form_contatti">
    
	<input name="name" type="text" placeholder=" Write here your name" id="campo_nome"/>
    <input name="company" type="text" placeholder=" Write here your company" id="campo_company"/>
    <input name="email" type="text" placeholder=" Write here your email" id="campo_email"/>
    <span class="Stile10">
    <textarea name="text" placeholder=" Write here your request" id="campo_testo"></textarea>
    </span>
    <a><input type="submit" id="pulsante_invio" value="Send"/></a>
  
  </form>
diventerebbe
PHP:
$messaggio->From="$_POST['email']";
$messaggio->AddAddress('[email protected]');
$messaggio->AddReplyTo...; <-- come devo scrivere per dirgli che deve rispondere sempre all'indirizzo presente nel campo "email"?
 

borgo italia

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
4 Feb 2008
16.046
150
63
PR
www.borgo-italia.it
ciao
$messaggio->AddReplyTo...; <-- come devo scrivere per dirgli che deve rispondere sempre all'indirizzo presente nel campo "email"?
di nuovo, se ti serve, $_POST['email']
 
Discussioni simili
Autore Titolo Forum Risposte Data
C Adattare uno script di altro linguaggio a javascript Javascript 11
M [Javascript] Adattare immagine di background all'altezza dello smartphone Javascript 1
L [HTML] Adattare bordo al contenuto HTML e CSS 4
D [Javascript] Convertire ed adattare una data Javascript 1
Juriy APP: Adattare immagini a GIF animata in real time Programmazione 0
B Adattare testo a cornice HTML e CSS 2
felino [CSS][Wordpress] Adattare delle immagini alla dimesione del box contenitore HTML e CSS 2
felino Adattare un layout desktop ad un responsive HTML e CSS 9
K Adattare app ad ogni schermo Sviluppo app per Android 1
L Adattare sfondo in base alla risoluzione WordPress 3
P Adattare sito alle varie risoluzioni... HTML e CSS 2
R Adattare immagini alla dimensione del monitor Javascript 2
P Risoluzione del sito si può adattare? HTML e CSS 0
V Adattare sito web per tutte le risoluzioni ? HTML e CSS 1
P Adattare sito a diverse risoluzioni HTML e CSS 14
S Adattare la pagina web creata ad ogni monitor HTML e CSS 11
W Adattare immagini slideshow a riquadro predefinito Webdesign e Grafica 0
matrobriva Adattare classe Odt2Xhtml PHP 2
F [HELP] Adattare al form Visual Basic 0
L Adattare il sito a qualsiasi computer Webdesign e Grafica 4
P Adattare un layer alle varie risoluzioni HTML e CSS 0
D Adattare contenuto a risoluzione utente HTML e CSS 5
G adattare sito con frame a monitor [era:Frame] Webdesign e Grafica 3
M Adattare iFrame HTML e CSS 5
B Adattare tabella a immagine di sfondo con Dreamweaver Cs3 Webdesign e Grafica 3
StefanoITA Adattare il sito alla risoluzione del visitatore HTML e CSS 5
M Adattare sito a risoluzione video [era:help me] HTML e CSS 6
G adattare pagina web a tutte le risoluzioni HTML e CSS 9
C Adattare un filmato a vari monitor Flash 5
C Adattare il sito a vari schrmi HTML e CSS 2
F Somma di più tabelle da script Javascript 0
L Script per convertire numeri in parole Javascript 2
H Eliminazione script. Photoshop 0
S Script Google Translate scomparso HTML e CSS 3
P lanciare script asp (o php) da jquery Javascript 1
G Script notifiche dekstop aiuto Javascript 0
G [PHP] Creare script di prenotazione con controllo disponibilità. PHP 7
P Passare solo alcuni parametri a script per CSV PHP 0
M Collegamento tra form html e script php PHP 4
F Script java elenco alfabetico non funziona Javascript 3
F Script non funzionante. Devo elencare in ordine alfabetico un elenco di nominativi, ma lo script non Javascript 2
P Script upload immagini jQuery 0
M Premature end of script headers PHP 1
Cosina script data aggiornamento pagina Javascript 1
R Distribuire uno Script "Facebook Auto Post" PHP 0
F Creazione script Tv Presentati al Forum 1
N Script elenco file HTML HTML e CSS 5
felino PHP e script generazione file excel PHP 2
MarcoGrazia Se non sai se riceverai da GET o da POST, puoi verificarlo e far scegliere allo script. Snippet PHP 0
Beppe2 Ritardare esecuzione script Javascript 2

Discussioni simili