web-dev-qa-db-fra.com

Les variables ne fonctionnent pas sous forme de courrier électronique

J'ai créé un simple formulaire de courrier électronique pour envoyer une pièce jointe (image). Toutes les informations sur l'expéditeur sont extraites de la base de données joomla. L'utilisateur sélectionne dans la liste déroulante (remplie à partir de la base de données) le nouveau nom de l'image.

  • Aux lignes 1 à 50, j'ai créé toutes les variables de la base joomala
  • Aux lignes 50-56, j'ai testé les variables avec echo et tout fonctionne
  • Dans le formulaire de courrier électronique, après la ligne 58, les variables $ alias et $ sender ne fonctionnent pas (obtenir de l’espace vide à la place de la valeur dans un message électronique)

    <?php
    // $link_id
    $link_id = JRequest::getInt('link_id');
    
    // $sender
    $db = JFactory::getDbo();
    $query1 = $db->getQuery(true);
    $query1->select('link_name');
    $query1->from($db->quoteName('#__hikers'));
    $query1->where($db->quoteName('#__hikers.link_id')." = ".$db->quote($link_id));
    $db->setQuery($query1);
    $sender = $db->loadResult();
    
    // $alias
    $db = JFactory::getDbo();
    $querya = $db->getQuery(true);
    $querya->select('#__hikers.alias');
    $querya->from($db->quoteName('#__hikers'));
    $querya->where($db->quoteName('#__hikers.link_id')." = ".$db->quote($link_id));
    $db->setQuery($querya);
    $alias = $db->loadResult();
    
    // $sender_email
    $db = JFactory::getDbo();
    $query3 = $db->getQuery(true);
    $query3->select('#__users.email');
    $query3->from($db->quoteName('#__users'));
    $query3->where($db->quoteName('#__users.id')." = ".$db->quote($userId));
    $db->setQuery($query3);
    $sender_email = $db->loadResult();
    
    // Dropdown menu from database
    
    $db = JFactory::getDbo();
    $squery = $db->getQuery(true);
    $squery->select('peak_name');
    $squery->from($db->qn('#__unclimbedpeaks'));
    $squery->where($db->quoteName('#__unclimbedpeaks.link_id')." = ".$db->quote($link_id));
    $squery->order('peak_id ASC');
    $db->setQuery($squery);
    $speaks_list = $db->loadColumn();
    $speaks_select  = '<select name="name" id="peaks">';
    $speaks_select .= '<option value="">-- Odaberi vrh --</option>';
    foreach($speaks_list as $p){
    $speaks_select .= '<option value="' . $p . '">' . $p . '</option>';  
        }
    $speaks_select .= '</select>';
    ?>
    <?php
    
    // Testing $alias, $sender, $sender_email and $link_id
    
    echo $alias;
    echo $sender;
    echo $sender_email;
    echo $link_id;
    
    // Email form
    
    if(isset($_POST['submit2']))
    {   $svrh_name = $_POST['name'];
        $output = header('Location: https://mysite/'.$alias); /* Redirect browser */;
        //Set the form flag to no display (cheap way!)
        $flags = 'style="display:none;"';
    
        //Deal with the email
        $to = '[email protected]';
        $subject = 'Message from '.$sender;
        $message = 'This is message with '.$svrh_name.' from '.$sender.'. Please visit link: https://MySite/'.$alias.' Sender email:'.$sender_email.' Sender ID:'.$link_id.'';
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $svrh_name.'.jpg';
        $boundary =md5(date('r', time())); 
        $headers = 'From: '.$sender_email.' \r\nReply-To: '.$sender_email.'';
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
        $message="This is a multi-part message in MIME format.
    
    --_1_$boundary
    Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
    
    --_2_$boundary
    Content-Type: text/plain; charset=\"iso-8859-1\"
    Content-Transfer-Encoding: 7bit
    
    $message
    
    --_2_$boundary--
    --_1_$boundary
    Content-Type: application/octet-stream; name=\"$filename\" 
    Content-Transfer-Encoding: base64 
    Content-Disposition: attachment 
    
    $attachment
    --_1_$boundary--";
    
        mail($to, $subject, $message, $headers);
    }
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"         "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>MailFile</title>
    </head>
    <body>
    <?php echo $output; ?>
    <form enctype="multipart/form-data" action="<?php echo         $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>>
    <?php echo $speaks_select; ?>
    <p><label for="file">File</label> <input type="file" name="file" id="file"></p>
    <p><input type="submit" name="submit2" id="submit2" value="Send"></p>
    </form>
    </body>
    </html> 
    
1
Midhat

Vos clauses where sont incorrectes. Vous n'avez pas besoin d'utiliser le nom de la table, seulement la colonne

Alors remplacez les clauses comme indiqué ci-dessous:


Requête 1:

$query1->where($db->quoteName('#__hikers.link_id')." = ".$db->quote($link_id));

avec:

$query1->where($db->quoteName('link_id')." = ".$db->quote($link_id));

Requête 2:

$querya->where($db->quoteName('#__hikers.link_id')." = ".$db->quote($link_id));

avec:

$querya->where($db->quoteName('link_id')." = ".$db->quote($link_id));

Requête 3:

$query3->where($db->quoteName('#__users.id')." = ".$db->quote($userId));

avec:

$query3->where($db->quoteName('id')." = ".$db->quote($userId));

Requête 4:

$squery->where($db->quoteName('#__unclimbedpeaks.link_id')." = ".$db->quote($link_id));

avec:

$squery->where($db->quoteName('link_id')." = ".$db->quote($link_id));

Plutôt que d'utiliser la fonction native mail() de PHP, je vous suggère d'utiliser le wrapp mail de Joomla, qui utilise PHPMailer, remplacez donc:

mail($to, $subject, $message, $headers);

Exemple à partir d'ici: https://docs.joomla.org/Sending_email_from_extensions

2
Lodder

Je pense qu'il y a un peu de mal avec votre code posté et il y a des détails essentiels qui ne sont pas inclus dans la question. Je vais commencer cette réponse au wiki afin que tout le monde puisse ajouter son expertise et corriger le bloc de code avec les meilleures pratiques. Ce qui suit n'a pas été testé.

$jinput = JFactory::getApplication()->input;
$link_id = (int)$jinput->get('link_id', 0, 'int');  // initally $_GET, but later $_POST
$submit = $jinput->post->get('submit2', '', 'string');
$peak = $jinput->post->get('peak', '', 'string');
$files = $jinput->files->get('file', [], 'array');

$db = JFactory::getDbo();  // just one reusable database connection / object

if ($submit != 'Send') {
    // pre-submission:
    try {
        $peaks_query = $db->getQuery(true)
                          ->select('peak_name')
                          ->from('#__unclimbedpeaks')
                          ->where("link_id = $link_id")
                          ->order('peak_id');
        $db->setQuery($peaks_query);
        $peaks_list = $db->loadColumn();
        $peaks_select = '<select name="peak" id="peak">';
        $peaks_select .= '<option value="">-- Odaberi vrh --</option>';
        foreach ($peaks_list as $p) {
            $peaks_select .= '<option value="' . htmlspecialchars($p, ENT_QUOTES) . '">' . $p . '</option>';
        }
        $peaks_select .= '</select>';
    } catch (Exception $e) {
        echo "Syntax Error @ unclimbedpeaks table"; //  , $e->getMessage();
    }
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>MailFile</title>
    </head>
    <body>
    <form enctype="multipart/form-data" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
        <p><label for="peak">Remaining Peaks</label> <?php echo $peaks_select; ?></p>
        <p><label for="file">File</label> <input type="file" name="file" id="file"></p>
        <p><input type="submit" name="submit2" id="submit2" value="Send"></p>
        <input type="hidden" name="link_id" value="$link_id">
    </form>
    </body>
    </html>
    <?php
} else {
    // post-submission
    try {
        $hiker_query = $db->getQuery(true)
                          ->select(array('link_name', 'alias'))
                          ->from('#__hikers')
                          ->where("link_id = $link_id");
        $db->setQuery($hiker_query);
        if (!$hiker = $db->loadAssoc()) {
            echo "Failed to find hiker";
        } else {
            $mailer = JFactory::getMailer();
            $user = JFactory::getUser();
            $sender_email = $user->email;
            $mailer->setSender($sender_email);

            $mailer->addRecipient('[email protected]');
            $mailer->setSubject('Message from ' . $hiker['link_name']);
            $mailer->setBody('This is message with ' . $peak . ' from ' . $hiker['link_name'] . '. Please visit link: https://MySite/' . $hiker['alias'] . ' Sender email:' . $sender_email . ' Sender ID:' . $link_id);
            /*
             * Not sure how to prepare the file attachment portion...
             * $mailer->addAttachment();
             */
            $send = $mailer->Send();
            if ($send === true) {
                echo 'Mail sent';
            } else {
                echo 'Error sending email';
            }
        }
    } catch (Exception $e) {
        echo "Syntax Error @ hiker table"; //  , $e->getMessage();
    }
}
0
mickmackusa