Rechercher : dans
Par :

Envoyer un fichier joint en php

mikil, le 5 aoû 2007 à 18:10:06 
 Signaler ce message aux modérateurs

Bonjour
je voudrai envoyer un fichier joint par un formulaire mais je n'y arrive pas donc j'ai fait des recherche sur internet essayer plusieur truc et j'ai touvais un truc le voici en 2 étapes comme je le veux

Form.html


DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <title>form</title>
</head>
<body>
<form method="post" action="envoi.php" enctype="multipart/form-data" name="form">
Exp&eacute;diteur: <input name="email" size="25" type="text"><br>

Destinataire: <input name="email_destinaire" size="25" type="text"><br>

Sujet : <input name="subject" size="25" type="text"><br>

Message : <textarea rows="5" name="message" cols="30"></textarea><br>

Fichier joint: <input name="MAX_FILE_SIZE" value="100000" type="hidden">
  <input name="NomFichier" size="16" type="file"><br>

Priorit&eacute;: 
  <select name="priorite" size="1">
  <option value="1">Urgent</option>
  <option value="2">Haute</option>
  <option value="3">Moyenne</option>
  <option value="4">Basse</option>
  <option value="5">Tr&egrave;s basse</option>
  </select>

  <br>

  <input value="Envoyer ce message" type="submit">
</form>

</body>
</html>




et envoi.php
<?php
/*----------------------- Installation -------------------------
Utilité >> Envoi un fichier fichier joint
Nom du fichier >> envoi.php
Créé le  >> 17/09/01

1°) Donner l'action du formulaire vers ce fichier
2°) Créer un repertoire (dossier) nommé "transit"
        à la racine de votre site,
        et mettez le en CHMOD 777
        (voir $NomFichier_name)

>> pour toutes informations >> http://www.akoter.com/forum/
--------------------------------------------------------------*/

$destinataire = $email_destinaire ;    // destinatiare du message
$copie_conforme = ""; // copie conforme
$cache_destinataire = ""; // email de surveillance
$objet_page = $subject ; // sujet du message
$redirection = "http://www.monsite.com/mapage.html"; // page de redrection dés le message envoyé
$priorite = $priorite ; // définition de la priorité du message
$reponse=StripSlashes("Votre message est envoyé ;o)"); // confirmation de l'envoi

// ----------------- début du Code ---------------------- //

class Mail {
        var $sendto= array();
        var $from, $msubject;
        var $acc= array();
        var $abcc= array();
        var $aattach= array();
        var $priorities= array( '1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)' );

function Mail() {
        $this->autoCheck(true);
}

function autoCheck($bool) {
    if($bool)
        $this->checkAddress = true;
    else
        $this->checkAddress = false;
}

function Subject($subject) {
        $this->msubject = strtr($subject, "\r\n" , "  " );
}

function From($from) {
    if( ! is_string($from) ) {
        echo "Class Mail: Erreur, From n'est pas de la bonne forme";
        exit;
    }

    $this->from= $from;
}

function To( $to ) {
    if( is_array( $to ) )
        $this->sendto= $to;
    else
        $this->sendto[] = $to;

    if( $this->checkAddress == true )
        $this->CheckAdresses( $this->sendto );
}

function Cc($cc) {
    if( is_array($cc) )
        $this->acc= $cc;
    else
        $this->acc[]= $cc;

    if( $this->checkAddress == true )
        $this->CheckAdresses( $this->acc );
}

function Bcc($bcc) {
    if( is_array($bcc) ) {
        $this->abcc = $bcc;
    } else {
        $this->abcc[]= $bcc;
    }
    if( $this->checkAddress == true )
        $this->CheckAdresses( $this->abcc );
}

function Body($body) {
    $this->body= $body;
}

function Send() {
    $this->_build_headers();
        if( sizeof( $this->aattach > 0 ) ) {
            $this->_build_attachement();
            $body = $this->fullBody . $this->attachment;
        }

    for( $i=0; $i< sizeof($this->sendto); $i++ ) { // envoie du mail aux destinataires principaux
            $res = mail($this->sendto[$i], $this->msubject,$body, $this->headers);
    }

}

function Organization($org) {
    if( trim( $org != "" )  )
        $this->organization= $org;
}

function Priority($priorite) {
    if( ! intval($priorite) )
        return false;

    if( ! isset($this->priorities[$priorite-1]) )
        return false;
    $this->priority= $this->priorities[$priorite-1];
    return true;
}

function Attach( $filename, $filetype='application/x-unknown-content-type', $disposition = "inline" ) {
    $this->aattach[] = $filename;
    $this->actype[] = $filetype;
    $this->adispo[] = $disposition;
}

function Get() {
    $this->_build_headers();
    if( sizeof( $this->aattach > 0 ) ) {
        $this->_build_attachement();
        $this->body= $this->body . $this->attachment;
    }
    $mail = $this->headers;
    $mail .= "\n$this->body";
    return $mail;
}

function ValidEmail($address) {
    if( ereg( ".*<(.+)>", $address, $regs ) ) {
        $address = $regs[1];
    }    
     if(ereg( "^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2}|net|fr|com|gov|mil|org|edu|int)\$",$address) )
         return true;
     else
         return false;
}

function CheckAdresses($aad) {
    for($i=0;$i< sizeof( $aad); $i++ ) {
        if( ! $this->ValidEmail( $aad[$i]) ) {
            echo "Class Mail, method Mail : Adresse Invalide $aad[$i]";
            exit;
        }
    }
}

function _build_headers() {// creation du header mail
$this->headers= "From: $this->from\n";
$this->to= implode( ", ", $this->sendto );

    if( count($this->acc) > 0 ) {
        $this->cc= implode( ", ", $this->acc );
        $this->headers .= "CC: $this->cc\n";
    }

    if( count($this->abcc) > 0 ) {
        $this->bcc= implode( ", ", $this->abcc );
        $this->headers .= "BCC: $this->bcc\n";
    }

    if( $this->organization != ""  )
        $this->headers .= "Organization: $this->organization\n";

    if( $this->priority != "" )
        $this->headers .= "X-Priority: $this->priority\n";
}

function _build_attachement() {
$this->boundary= "------------" . md5( uniqid("myboundary") ); // TODO : variable bound

$this->headers .= "MIME-Version: 1.0\nContent-Type: multipart/mixed;\n boundary=\"$this->boundary\"\n\n";
$this->fullBody = "This is a multi-part message in MIME format.\n--$this->boundary\nContent-Type: text/plain; charset=us-ascii\nContent-Transfer-Encoding: 7bit\n\n".$this->body."\n";
$sep= chr(13) . chr(10);

$ata= array();
$k=0;

    for( $i=0; $i < sizeof($this->aattach); $i++) {
            $filename = $this->aattach[$i];
            $basename = basename($filename);
            $ctype = $this->actype[$i]; 
            $disposition = $this->adispo[$i];

            if( ! file_exists( $filename) ) {
                    echo "Class Mail, method attach : file $filename can't be found"; exit;
            }

            $subhdr= "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
            $ata[$k++] = $subhdr;
            // non encoded line length
            $linesz= filesize($filename)+1;
            $fp= fopen( $filename, 'r' );
            $data= base64_encode(fread( $fp, $linesz));
            fclose($fp);
            $ata[$k++] = chunk_split( $data );
        }
    $this->attachment= implode($sep, $ata);
    }
} 

function redir($redirection) { // redirection JavaScript
    echo "<script language=\"javascript\">";
    echo "window.location=('".$redirection."');";
    echo "</script>";
}

$subject=StripSlashes($subject);

$msg=StripSlashes($msg); // construction du message email
$msg ="Message depuis votre site web :\n\n" ;
$msg .= "Subjet : ".$objet_page."\n" ;
$msg .= "Message : ".$message ;

$m= new Mail; // création du email
    $m->From($email);  // création du destinataire
    $m->To($destinataire); // création de l'expéditeur
    $m->Subject($subject); // création du sujet
    $m->Body($msg); // création du message

if ($copie_conforme!='') { //S'il y a une copie conforme du mail
    $m->Cc($copie_conforme);
}
    $m->Priority($priorite) ;   

if ($cache_destinataire!='') { //S'il y a une copie cachée du mail
    $m->Bcc($cache_destinataire);
}
    $m->Priority($priorite) ; 

if ($NomFichier_name !='') { // attache le fichier joint
    copy($NomFichier,"./transit/".$NomFichier_name."");
    $m->Attach( "./transit/".$NomFichier_name."", "application/octet-stream" );
}

    $m->Send(); /* Envoi du mail */

if ($NomFichier_name!='') {
    Unlink("./transit/".$NomFichier_name."");
    }

echo $reponse ;// Affichage du message d'envoi réussi

if ($redirection !='') {
    redir($redirection); // renvoie sur une page spécifique
}
?> 




Mais moi je n'est pas appris le code php comme ce la moi mon formulaire est:

recrutement.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


  
  <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">

  
  <title>recrutement</title>
</head>


<body>


<form style="width: 448px;" method="post" action="recrutement.php" name="recrutement">
  
  <div style="text-align: right;"></div>


  
  <table style="text-align: left; height: 299px; width: 426px;" border="0" cellpadding="2" cellspacing="2">


    <tbody>


      <tr>


        <td style="text-align: right; width: 111px;">Vous
souhaitez :</td>


        <td style="width: 298px;">
        
        <select name="souhait">
        <option selected="selected">NEGOCIATEUR (TRICE)</option>
        <option>DEMARCHEUR (EUSE)</option>
        <option>ASSISTANT(E) COMMERCIALE</option>
        <option>AUTRE...</option>
        </select>


        </td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;">Experience
:</td>


        <td style="width: 298px;">
        
        <select name="Experience">
        <option>Aucune</option>
        <option>- de 1 ans</option>
        <option>De 1 &agrave; 5 ans</option>
        <option>+5 ans</option>
        </select>


        </td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;">Ville
:</td>


        <td style="width: 298px;"><input size="10" name="ville"></td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;">Pr&eacute;nom
:</td>


        <td style="width: 298px;"><input name="prenom"></td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;">Nom :</td>


        <td style="width: 298px;"><input name="NOM"></td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;"><span style="font-weight: bold;">E-mail :</span></td>


        <td style="width: 298px;"><input name="e-mail"></td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;"><span style="font-weight: bold;">T&eacute;lephone :</span></td>


        <td style="width: 298px;"><input maxlength="13" name="telephone"></td>


      </tr>


      <tr>


        <td style="text-align: right; width: 111px;"><span style="font-weight: bold;">Votre CV</span> :<br>
        <br>

        </td>


        <td style="width: 298px;"><input name="MAX_FILE_SIZE" value="200000" type="hidden">
        <input name="NomFichier" size="15" type="file">&nbsp;<br>

(Format Word, Excel, PDF...)</td>



      </tr>


      <tr>


        <td style="text-align: right; height: 95px; width: 111px;">Commentaire
:<br>


        <br>


        <br>


        <br>


        </td>


        <td style="height: 95px; width: 298px;"><textarea wrap="soft" cols="30" rows="4" name="commentaire"></textarea></td>


      </tr>


    
    </tbody>
  
  </table>
  <div style="text-align: center;"><input name="Envoyer" value="Envoyer" type="submit"></div>
</form>


</body>
</html>





et recrutement.php (je l'ai appris comme cela)
<?php


 $sujet = date("d/m/Y H:i:s" )." (nouveaux bien)";

 $contenu = "";

 $contenu .= "Souhait : ".$_POST['souhait']."\n";

 $contenu .= "Experience : ".$_POST['Experience']."\n";

 $contenu .= "Prenom : ".$_POST['prenom']."\n";

 $contenu .= "Nom : ".$_POST['NOM']."\n";

 $contenu .= "E-mail : ".$_POST['e-mail']."\n";

 $contenu .= "Telephone : ".$_POST['telephone']."\n";

 $contenu .= "Mobile : ".$_POST['Mobile']."\n";

 $contenu .= "CV: ".$_POST['NomFichier']."\n";

 $contenu .= "Commentaire : ".$_POST['commentaire']."\n";



if(mail("comert33@yahoo.fr", $sujet, $contenu))

 {

  print "<b>Mail envoyé

<br> 

<a

 style=\"text-decoration: underline; font-weight: bold; color: rgb(51, 51, 255);\"

 href=\"index.html\">RETOUR à l'accueil</a>

</b>";

 } 

else 

{

  print "<b>Erreur</b>";

}



?>



Donc je ne comprend pas le premier formulaire.
Pouvez vous m'aider a modifier le 2ieme formulaire pour qu'il envois des piece jointe comme le 1er formulaire?

cordialement
Configuration: Windows XP
Internet Explorer 6.0

Meilleures réponses pour « Envoyer un fichier joint en php » dans :
[PHP] Upload de fichiers VoirLe langage PHP permet de gérer des fichiers envoyés (uploadés) grâce à un formulaire HTML. Formulaire d'envoi de fichiers Configuration de PHP pour permettre l'upload Récupération du fichier avec PHP Formulaire d'envoi de fichiers La...
Envoyer des fichiers volumineux par mail VoirEnvoyer de gros fichiers à des amis par courrier électronique n'est pas toujours facile. La plupart des serveurs de messagerie n'acceptent pas des fichiers de taille supérieure à 5 Mo. Néanmoins, il existe des solutions alternatives : Les serveurs...
[Langages] Envoyer un mail avec pièce jointe VoirLes mails, tout comme les pages web, sont livrés avec des en-têtes (headers en anglais). Ces en-têtes servent à donner quelques détails nécessaires comme l'adresse du destinataire, celle de l'envoyeur, la date de l'envoi, le sujet du mail etc. Elles...
PHP - Les fichiers VoirLa gestion des fichiers avec PHP Avec PHP, la création ou la lecture de fichiers est, une fois de plus, assez simple. Il existe une multitude de fonctions dédiées à l'utilisation des fichiers. La communication entre le script PHP et le fichier...