IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Pièce jointe dans un formulaire


Sujet :

Langage PHP

  1. #1
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2004
    Messages : 37
    Points : 19
    Points
    19
    Par défaut Pièce jointe dans un formulaire
    Bonjour à tous,

    Je retape actuellement un site qui contient une page contenant un formulaire incluant l'ajout d'une pièce jointe.

    J'ai cherché sur Internet pendant des heures, trouvant diverses pages me proposant des solutions que j'ai tenté d'adapter à mes besoins, mais je n'y parvient simplement pas.

    j'ai notamment trouvé cette page : http://a-pellegrini.developpez.com/t...php/mail/#L3.4
    que je l'ai transformé en :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    <?
     
    // Récupération des information du formulaire
     
    $to = 'adresse-du-destinataire@domaine.com';
    $name = $_POST['name'];
    $from = $_POST['from'];
    $tel = $_POST['tel'];
    $object = $_POST['object'];
    $contenu = $_POST['contenu'];
     
    // clé aléatoire de limite
    $boundary = md5(uniqid(microtime(), TRUE));
     
    // Headers
    $headers = 'From: '.$from."\r\n";
    $headers .= 'Mime-Version: 1.0'."\r\n";
    $headers .= 'Content-Type: multipart/mixed;boundary='.$boundary."\r\n";
    $headers .= "\r\n";
     
    // Message HTML
    $msg  = '--'.$boundary."\r\n";
    $msg .= 'Content-type: text/html; charset=\"iso-8859-1\"'."\r\n\r\n";
    $msg .= 'Nom : '.$name."<br>";
    $msg .= 'Tél : '.$tel."<br><br>";
    $msg .= $contenu."\r\n";
     
    // Pièce jointe 1
    $file_name = $_FILES['piece_jointe'];
    if (file_exists($file_name))
    {
    	$file_type = filetype($file_name);
    	$file_size = filesize($file_name);
     
    	$handle = fopen($file_name, 'r') or die('File '.$file_name.'can t be open');
    	$content = fread($handle, $file_size);
    	$content = chunk_split(base64_encode($content));
    	$f = fclose($handle);
     
    	$msg .= '--'.$boundary."\r\n";
    	$msg .= 'Content-type:'.$file_type.';name='.$file_name."\r\n";
    	$msg .= 'Content-transfer-encoding:base64'."\r\n\r\n";
    	$msg .= $content."\r\n";
    }
     
    // Fin
    $msg .= '--'.$boundary."\r\n";
     
    // Function mail()
    mail($to, $object, $msg, $headers);
    Et voici mon formulaire :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <form id='soumission' method="post" enctype="multipart/form-data" action="<?php echo( $_SERVER['REQUEST_URI'] ); ?>">  
    <label for="name">Votre nom</label><input type="text" name="name" id="name" size="25" value="<?php echo( $name ); ?>" />
    <label for="mail">Votre adresse mail</label><input type="text" name="from" id="from" size="25" value="<?php echo( $from ); ?>" /> 
    <label for="tel">Votre téléphone</label><input type="text" name="tel" id="tel" size="25" value="<?php echo( $tel ); ?>" />
    <label for="object">Objet</label><input type="text" name="object" id="object" size="25" value="<?php echo( $object ); ?>" />
    <label for="contenu">Message</label><textarea name="contenu" id="contenu" rows="10" cols="70"><?php echo( $contenu ); ?></textarea>
    <label for="fichier">Piece jointe</label><input type="file" name="piece_jointe" id="piece_jointe" />
    <input type="reset" name="reset" value="Effacer" /><input type="submit" name="send" value="Envoyer" />
    </form>
    Mais cela ne fonctionne pas. Le mail est bien envoyé avec toutes les données, mais la pièce jointe n'apparaît pas. Pourriez-vous m'aider à trouver mon/mes erreur(s) et me dire ce que je dois modifier pour que le formulaire fonctionne pour l'envoie de fichiers (.doc, .pdf ou autre).

    D'avance un grand merci de votre aide

    Thufir Hawat

  2. #2
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2004
    Messages : 37
    Points : 19
    Points
    19
    Par défaut
    Re Bonjour,

    Ayant continué à creuser la question j'ai fait quelques modifications en me basant sur ce code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    $headers = 'From: '.$email;
     
    		$content .= 'Le texte de mon message (en html si je veux)';
     
    		if ($_FILES["fichier"]["name"] != null) {
     
    			$fileatt = $_FILES['fichier']['tmp_name'];
    			$fileatt_type = $_FILES['fichier']['type'];
    			$fileatt_name = $_FILES['fichier']['name'];
     
    			if (is_uploaded_file($fileatt)) {
    				// Read the file to be attached
    				$file = fopen($fileatt,'rb');
    				$data = fread($file,filesize($fileatt));
    				fclose($file);
     
    				// Generate a boundary string
    				$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
    				$msg = "--{$mime_boundary}\n" .
    					"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
    					"Content-Transfer-Encoding: 7bit\n\n" .
    					$content . "\n\n";
     
    				// Base64 encode the file data
    				$data = chunk_split(base64_encode($data));
     
    				// Add file attachment to the message
    				$msg .= "--{$mime_boundary}\n" .
    					"Content-Type: {$fileatt_type};\n" .
    					" name=\"{$fileatt_name}\"\n" .
    					"Content-Disposition: inline;\n" .
    					" filename=\"{$fileatt_name}\"\n" .
    					"Content-Transfer-Encoding: base64\n\n" .
    					$data . "\n\n" .
    					"--{$mime_boundary}--\n";
    				$messageEnvoye = mail($_GET['email'],$objet,$msg,$headers);
    			} else {
    				// Fichier trop gros => gerer erreur
    			}
    		} else {
    			$headers ='MIME-Version: 1.0' . "\n";
    			$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n";
    			$headers .= 'From: '.$email."\n";
    			$headers .= "\n";
    			$messageEnvoye = mail($_GET['email'],$objet,$content,$headers);
    		}
    que j'ai trouvé ici : http://forum.ovh.com/showthread.php?t=11748

    Je l'ai adapté à ma sauce et j'ai découvert que le problème se situait au niveau de la fonction is_uploaded_file() qui renvoie systématiquement FALSE. Problème de taille du fichier ? (pourtant je fais des tests avec un fichier .jpg très léger). J'espère que ces précisions pourront vous permettre de m'aider à résoudre mon problème.

    Thufir Hawat

  3. #3
    Modérateur
    Avatar de sabotage
    Homme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    29 208
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juillet 2005
    Messages : 29 208
    Points : 44 155
    Points
    44 155
    Par défaut
    Controle ce que contient ton $_FILES.
    N'oubliez pas de consulter les FAQ PHP et les cours et tutoriels PHP

  4. #4
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2004
    Messages : 37
    Points : 19
    Points
    19
    Par défaut suite
    J'ai fait un var_dump sur mon $_FILES et j'obtiens les infos suivante :

    array(5) { ["name"]=> string(11) "fichier.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpnDid08" ["error"]=> int(0) ["size"]=> int(39367) }

    Désormais je reçois le mail mais sous une forme étrange :

    MIME-Version: 1.0
    Content-Type: multipart/mixed;
    boundary="==Multipart_Boundary_x2b3474332a0bfa968867800e49e9ba8cx"

    --==Multipart_Boundary_x2b3474332a0bfa968867800e49e9ba8cx
    Content-Type: text/html; charset="iso-8859-1"
    Content-Transfer-Encoding: 7bit

    יייייייי

    --==Multipart_Boundary_x2b3474332a0bfa968867800e49e9ba8cx
    Content-Type: image/jpeg;
    name="fichier.jpg"
    Content-Disposition: inline;
    filename="fichier.jpg"
    Content-Transfer-Encoding: base64

    /9j/4RcaRXhpZgAASUkqAAgAAAAPAAABAwABAAAAAAgAAAEBAwABAAAAAAYAAAIBAwADAAAAwgAA
    AAYBAwABAAAAAgAAAA8BAgAGAAAAyAAAABABAgAEAAAARTcxABIBAwABAAAAAQAAABUBAwABAAAA
    AwAAABoBBQABAAAAzgAAABsBBQABAAAA1gAAACgBAwABAAAAAgAAADEBAgAcAAAA3gAAADIBAgAU
    AAAA+gAAABMCAwABAAAAAQAAAGmHBAABAAAAEAEAADgCAAAIAAgACABOb2tpYQDAxi0AECcAAMDG
    LQAQJwAAQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzADIwMTI6MTI6MDEgMjA6MTk6MTIAAAAS
    AJ2CBQABAAAA7gEAAACQBwAEAAAAMDIyMAOQAgAUAAAA9gEAAASQAgAUAAAACgIAAAGRBwAEAAAA
    AQIDAAKSBQABAAAAHgIAAAiSAwABAAAABAAAAAmSAwABAAAAGQAAAAqSBQABAAAAJgIAAACgBwAE
    AAAAMDEwMAGgAwABAAAAAQAAAAKgBAABAAAAzgMAAAOgBAABAAAAEgUAAAGkAwABAAAAAAAAAAKk
    AwABAAAAAAAAAAOkAwABAAAAAAAAAASkBQABAAAALgIAAAakAwABAAAAAAAAAAAAAAAgAAAACgAA
    ADIwMTA6MTA6MDggMjA6MTM6MTkAMjAxMDoxMDowOCAyMDoxMzoxOQBAAQAAZAAAADEAAAAKAAAA
    ZAAAAGQAAAAAAAYAAwEDAAEAAAAGAAAAGgEFAAEAAACGAgAAGwEFAAEAAACOAgAAKAEDAAEAAAAC
    AAAAAQIEAAEAAACWAgAAAgIEAAEAAAB8FAAAAAAAAEgAAAABAAAASAAAAAEAAAD/2P/tAAxBZG9i
    ZV9DTQAB/+4ADkFkb2JlAGSAAAAAAf/bAIQADAgICAkIDAkJDBELCgsRFQ8MDA8VGBMTFRMTGBEM
    DAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAENCwsNDg0QDg4QFA4ODhQUDg4ODhQR
    DAwMDAwREQwMDAwMDBEMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM/8AAEQgAoAB4AwEiAAIR
    AQMRAf/dAAQACP/EAT8AAAEFAQEBAQEBAAAAAAAAAAMAAQIEBQYHCAkKCwEAAQUBAQEBAQEAAAAA
    AAAAAQACAwQFBgcICQoLEAABBAEDAgQCBQcGCAUDDDMBAAIRAwQhEjEFQVFhEyJxgTIGFJGhsUIj
    JBVSwWIzNHKC0UMHJZJTHxY3M1FqKygyZEk1RkRcKjdDYX0lXiZfKzhMPTdePzRieUpIW0lcTU
    5PSltcXV5fVWZnaGlqa2xtbm9jdHV2d3h5ent8fX5/cRAAICAQIEBAMEBQYHBwYFNQEAAhEDITES
    BEFRYXEiEwUygZEUobFCI8FS0fAzJGLhcoKSQ1MVY3M08SUGFqKygwcmNcLSRJNUoxdkRVU2dGXi
    etc...
    Comme si je reçevais le code de mon fichier au lieu du mail à proprement parler.

    Revoilà mon code à ce stade :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    <?
    var_dump($_FILES['piece_jointe']);
     
    if ($_FILES["piece_jointe"]["name"] != null) { 
     
    // Récupération des information du formulaire
     
    $to = monadressemail@domaine.com
    $name = $_POST['name'];
    $from = $_POST['from'];
    $tel = $_POST['tel'];
    $object = $_POST['object'];
    $contenu = $_POST['contenu'];
     
     
    			$fileatt = $_FILES['piece_jointe']['tmp_name'];
    			$fileatt_type = $_FILES['piece_jointe']['type'];
    			$fileatt_name = $_FILES['piece_jointe']['name'];
     
    			if (is_uploaded_file($fileatt)) {
    				// Read the file to be attached
    				$file = fopen($fileatt,'rb');
    				$data = fread($file,filesize($fileatt));
    				fclose($file);
     
    				// Generate a boundary string
    				$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
    				$msg = "--{$mime_boundary}\n" .
    					"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
    					"Content-Transfer-Encoding: 7bit\n\n" .
    					$contenu . "\n\n";
     
    				// Base64 encode the file data
    				$data = chunk_split(base64_encode($data));
     
    				// Add file attachment to the message
    				$msg .= "--{$mime_boundary}\n" .
    					"Content-Type: {$fileatt_type};\n" .
    					" name=\"{$fileatt_name}\"\n" .
    					"Content-Disposition: inline;\n" .
    					" filename=\"{$fileatt_name}\"\n" .
    					"Content-Transfer-Encoding: base64\n\n" .
    					$data . "\n\n" .
    					"--{$mime_boundary}--\n";
     
    				$messageEnvoye = mail($to,$object,$msg,$headers);
     
     
    		} else {
    	echo "trop gros";			// Fichier trop gros => gerer erreur
    			}
    }
    et mon formulaire situé sur la même page est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    <form id='soumission' method="post" enctype="multipart/form-data" action="<?php echo( $_SERVER['REQUEST_URI'] ); ?>">  
    <label for="name">Votre nom</label><input type="text" name="name" id="name" size="25" value="<?php echo( $name ); ?>" />
    <label for="from">Votre adresse mail</label><input type="text" name="from" id="from" size="25" value="<?php echo( $from ); ?>" />
    <label for="tel">Votre téléphone</label><input type="text" name="tel" id="tel" size="25" value="<?php echo( $tel ); ?>" />
    <label for="object">Objet</label><input type="text" name="object" id="object" size="25" value="<?php echo( $object ); ?>" />
    <label for="contenu">Message</label><textarea name="contenu" id="contenu" rows="10" cols="70"><?php echo( $contenu ); ?></textarea>
    <label for="piece_jointe">Piece jointe</label><input type="hidden" name="MAX_FILE_SIZE" value="2000000" /><input type="file" name="piece_jointe" id="piece_jointe" />
    <input type="reset" name="reset" value="Effacer" /><input type="submit" name="send" value="Envoyer" />
    </form>
    Une idée ?

  5. #5
    Membre à l'essai
    Profil pro
    Inscrit en
    Mars 2004
    Messages
    37
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Mars 2004
    Messages : 37
    Points : 19
    Points
    19
    Par défaut suite et fin
    Bonjour,

    N'ayant pas mis tous mes oeufs dans le même panier, j'ai également posté sur un autre forum où j'ai reçu la réponse salvatrice. J'ajoute donc la correction ici si ça peut servir à quelqu'un.

    Dans mon code il fallait remplacer
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";
    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    $headers = 'MIME-Version: 1.0'."\n"; 
    $headers .= 'Content-Type: multipart/mixed; boundary="'.$mime_boundary.'"';
    Avec quelques modifications supplémentaires pour la mise en forme, le contrôle des erreurs et l'affichage de toutes les données dans le mail, mais au moins cela fonctionne.

    Merci à sabotage pour son aiguillage et merci à c00lman sur l'autre forum.

  6. #6
    Membre à l'essai
    Inscrit en
    Mai 2004
    Messages
    7
    Détails du profil
    Informations forums :
    Inscription : Mai 2004
    Messages : 7
    Points : 11
    Points
    11
    Par défaut
    Salut à tous.
    J'ai essayé de reprendre le code de cette discussion de l'adapter, de chercher ailleurs sur le net, mais pas moyen de faire fonctionner pour moi.
    Je reçois un mail vide... pas de pièce jointe pas de texte...
    Ci dessous mon bout de code.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    // clé aléatoire de limite
    $boundary = md5(uniqid(microtime(), TRUE));
     
    // Headers
    $headers='From: Monsieur <contact@blabla.com>'."\r\n";
    $headers .= 'X-Priority: 1 '."\n";
    $headers .= 'Mime-Version: 1.0'."\r\n";
    $headers .= 'Content-Type: multipart/mixed; boundary='.$boundary."\r\n";
    $headers .= "\r\n";
     
     
    // Texte
    $msg .= '--'.$boundary." \r\n";
    $msg .= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
    $msg .= 'Content-Transfer-Encoding:8bit '."\r\n";
    $msg .= 'Un message avec une pièce jointe.'."\r\n";
     
    // Pièce jointe
    $fileatt = $_FILES['piece_jointe']['tmp_name'];
    $fileatt_type = $_FILES['piece_jointe']['type'];
    $fileatt_name = $_FILES['piece_jointe']['name'];
    if (file_exists($fileatt))
    {
    	$file_type = filetype($fileatt);
    	$file_size = filesize($fileatt);
     
    	$handle = fopen($fileatt, 'r'); // or die('File '.$fileatt_name.'can t be open');
    	$content = fread($handle, $file_size);
    	$content = chunk_split(base64_encode($content));
    	$f = fclose($handle);
     
    	$msg .= '--'.$boundary."\r\n";
    	$msg .= 'Content-Type:'.$file_type.'; name='.$fileatt_name."\r\n";
    	$msg .= 'Content-Transfer-Encoding: base64'."\r\n";
    	$msg .= 'Content-Disposition: attachment; filename='.$fileatt_name." \n";  
    	$msg .= $content."\r\n";
    }
     
    // Fin
    $msg .= '--'.$boundary.'--'."\r\n";
     
    // Function mail()
    mail('moi@toto.fr', $subject, $msg, $headers);
    JE suis preneur du moindre tuyau!
    Merci d'avance.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Multiples pièces jointes dans un formulaire pour mail
    Par infovect dans le forum Langage
    Réponses: 1
    Dernier message: 12/07/2014, 16h45
  2. [OL-97] inserer une pièce jointe dans un formulaire
    Par maniveaudelaye dans le forum Outlook
    Réponses: 0
    Dernier message: 30/10/2012, 21h31
  3. [AC-2010] Insertion pièce jointe dans une table via un formulaire
    Par Kenny66 dans le forum Access
    Réponses: 2
    Dernier message: 14/02/2012, 16h02
  4. [MySQL] envoyer fichier chargé par formulaire an tant que pièce joint dans l'Email de destination
    Par all4youweb dans le forum PHP & Base de données
    Réponses: 3
    Dernier message: 07/07/2010, 10h35
  5. [SP-2007] Pièce jointe dans un formulaire personnalisé
    Par Socki dans le forum SharePoint
    Réponses: 6
    Dernier message: 04/06/2009, 14h27

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo