1

I made a simple email form to send an attachment (image). All sender information is taken from the joomla database, the user selects from the dropdown list (populated from database) new name of image.

  • In lines 1-50, I created all the variables from the joomala base
  • In lines 50-56 I have tested variables with echo and everything works
  • In email form after line 58 variables $alias and $sender does not work (get empty space instead of value in email message)

    <?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 = 'admin@MySite.com';
        $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
    JRequest is deprecated. Please use JInput – Lodder Jan 24 '18 at 11:32
  • Thank you. I tried to change it, but it still does not work – Midhat Jan 24 '18 at 12:33
  • What are you expecting from $output = header('Location: https://mysite/'.$alias); /* Redirect browser */; header() doesn't offer a return value. Are you trying to exit the script prematurely and load the new page? – mickmackusa Jul 24 '18 at 9:40
  • @When you say $alias and $sender don't work, is that to mean that the other variables DO contain their expected values? Have you implemented Lodder's advice to use Joomla's mailing technique? You should try to reduce your total calls to the database by 1. merging the $sender and $alias queries and 2. only query for $speaks_select when you are building your form. You should not be using display:none as a short cut, you should be using an if/else block to isolate pre-submission and post-submission processes. – mickmackusa Jul 24 '18 at 23:26
  • When your page is first loaded, do you have a url with ?link_id=[integer]? What happens when you submit (POST) your form? Your $_GET['link_id'] data is lost isn't it? $_SERVER['PHP_SELF'] is delivering the script, but not your querystring. I think you should be retaining the link_id during form submission by writing a hidden input field. – mickmackusa Jul 24 '18 at 23:31
2

Your where clauses are incorrect. You don't need to use the table name, only the column

So replace the clauses as shown below:


Query 1:

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

with:

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

Query 2:

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

with:

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

Query 3:

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

with:

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

Query 4:

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

with:

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

Rather than using PHP's native mail() function, I suggest you utilise Joomla's mail wrapp which uses PHPMailer, so replace:

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

Example from here: https://docs.joomla.org/Sending_email_from_extensions

| improve this answer | |
  • Thank you, I made these updates, but I have the same result. Variables work when I test them with echo, but they do not work in email form – Midhat Jan 24 '18 at 13:27
  • 1
    @Midhat - I've updated my answer. Please refer to the Joomla documentation as you should be using Joomla's API for your code. – Lodder Jan 24 '18 at 14:12
  • Is it possible to send file using Joomla's API ? – Midhat Jan 24 '18 at 16:13
  • 1
    Yes, it's possible. Please refer to the documentation link I added in my answer – Lodder Jan 24 '18 at 16:17
  • @Lodder the bulk of your answer is not true. Explicitly identifying the tablename for each column in the WHERE clauses will not cause trouble (though I'll agree that it is needless for this case). Please consider trimming/rewording your advice about the queries. There is A LOT to fix with the question. On Stackoverflow, I'd say this question is Too Broad, Unclear, and/or Why isn't my code working. JSX has a more forgiving culture, but in its current state this page is going to be mostly useless to future researchers and appear forever abandoned. How do you suggest we proceed? – mickmackusa Jul 24 '18 at 23:22
0

I feel that there is quite a bit wrong with your posted code and there are essential details that are not included in the question. I'll start this Wiki-answer so that anyone can add their expertise and correct the code block with best practices. The following was not tested.

$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('admin@mysite.com');
            $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();
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.