从管理仪表板通过电子邮件发送附件时出现问题

时间:2018-05-08 09:01:58

标签: php opencart email-attachments email-integration

登录管理信息中心并点击上传图片后,需要上传图片文件,并且应该通过电子邮件将该特定图片作为附件发送。两者都同时发生。

但在这里我只能将此图像保存到oc_upload表。但我无法通过电子邮件将该特定图像作为附件发送,这是我的以下代码。

模板文件(嵌套表单和JavaScript)

<div class="panel panel-default">
    <div class="panel-body">
        <form id="ms-sellerinfo" class="form-horizontal">
            <input type="hidden" id="seller_id" name="seller[seller_id]" value="<?php echo $seller['seller_id']; ?>" />
            <div class="tab-pane" id="tab-user-details">            
                <form  action="index.php?route=multimerch/seller/userdetails&token=<?php echo $token; ?>" method="post" enctype="multipart/form-data" > </form>

                <form action="index.php?route=multimerch/seller/userdetails&token=<?php echo $token;?>&seller_id=<?php echo $seller['seller_id'];?>" method="post" enctype="multipart/form-data">
                    <div class="form-group required">
                        <label class="col-sm-2 control-label" for="input-file">Upload Image</label>
                        <div class="col-sm-10">
                            <input type="file" name="file" id="file" class="file_input"  />
                            <button type="button" id="uploadimage" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-default"><i class="fa fa-upload"></i> Upload Image</button>
                            <input type="hidden" name="custom_field" value="" />
                            <input type="hidden" name="photo" />
                            <div id="demo"></div>
                        </div>
                    </div>
                <input type="submit" style="float:right;" name="submit" value="Submit"/>
                </form> 
            </div>
        </form>
    </div>
</div>


<script type="text/javascript">

$('button[id^=\'uploadimage\']').on('click', function() {
  var node = this;

  $('#form-upload').remove();

  $('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');

  $('#form-upload input[name=\'file\']').trigger('click');

  timer = setInterval(function() {
    if ($('#form-upload input[name=\'file\']').val() != '') {
    var fileName = $('#form-upload input[name=\'file\']').val()
    var ext = fileName.split('.').pop();
    var formData = new FormData($('#form-upload')[0]);
    formData.append('CustomerId', 2);  
    clearInterval(timer);

      $.ajax({
        url: 'index.php?route=customer/customer/test&token=<?php echo $token; ?>',
        type: 'post',
        dataType: 'json',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function() {
          $(node).button('loading');
        },
        complete: function() {
          $(node).button('reset');
        },
        success: function(json) {
          $(node).parent().find('.text-danger').remove();

          if (json['error']) {
            $(node).parent().find('input').after('<div class="text-danger">' + json['error'] + '</div>');
          }
          if (json['success']) {
            alert(json['success']);
            $(node).parent().find('input').attr('value', json['code']);
            $(node).parent().find('input[name=photo]').attr('value', json['photo']);         
            document.getElementById("demo").innerHTML = '<img src="' + json['photo'] +'" width="100px" height="100px">';            
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    }
  }, 500);
});
</script>

控制器文件

public function test(){

    $file_name = new SplFileInfo($this->request->files['file']['name']);
    $file_extension = $file_name->getExtension(); // die;

    $json = array();

    if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
        // Sanitize the filename
        $filename = basename(preg_replace('/[^a-zA-Z0-9\.\-\s+]/', '', html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8')));

        // Validate the filename length
        if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 64)) {
            $json['error'] = "Filename must be between 3 and 64 characters!";
        }

        // Allowed file extension types
        $allowed = array();

        $extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));

        $filetypes = explode("\n", $extension_allowed);

        foreach ($filetypes as $filetype) {
            $allowed[] = trim($filetype);
        }

        if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
            $json['error'] = "Invalid file type!";
        }

        // Allowed file mime types
        $allowed = array();

        $mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));

        $filetypes = explode("\n", $mime_allowed);

        foreach ($filetypes as $filetype) {
            $allowed[] = trim($filetype);
        }

        if (!in_array($this->request->files['file']['type'], $allowed)) {
            $json['error'] = "Invalid file type!";
        }

        // Check to see if any PHP files are trying to be uploaded
        $content = file_get_contents($this->request->files['file']['tmp_name']);

        if (preg_match('/\<\?php/i', $content)) {
            $json['error'] = "Invalid file type!";
        }

        // Return any upload error
        if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
            $json['error'] = 'Upload required!_' . $this->request->files['file']['error'];
        }
    } else {
        $json['error'] = "Upload required!";
    }

    if (!$json) {
        $file = $filename . '.' . token(32);
        move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);

        // Instead of calling model from 'tool/upload' i.e, addUpload($filename, $file); directly written in controller

            $code = sha1(uniqid(mt_rand(), true));
            $this->db->query("INSERT INTO `" . DB_PREFIX . "upload` SET `name` = '" . $this->db->escape($filename) . "', `filename` = '" . $this->db->escape($filename) . "', `code` = '" . $this->db->escape($file) . "', `date_added` = NOW()");

        $json['code'] = $code;
        $json['success'] = "Your file was successfully uploaded!";
        $json['photo'] = DIR_UPLOAD_PREV . $file;
        //echo '<pre>'; print_r($json); die;
        $emailseller='nishanth@xyz.in';
        $mail = new Mail();
        $mail->protocol = $this->config->get('config_mail_protocol');
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
        $mail->smtp_username = $this->config->get('config_mail_smtp_username');
        $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
        $mail->smtp_port = $this->config->get('config_mail_smtp_port');
        $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
        $mail->setTo($emailseller);
        $mail->setFrom($this->config->get('config_email'));
        $mail->setSender($this->config->get('config_email'));
        $subject = $mailing_details['cdetails']['customer_invoice']['invoice_no'];
        $mail->setSubject("Invoice Receipt");
        $mail->setHtml($this->load->view('mail/order', $data));
        $mail->setText("Test");
        $mail->AddAttachment($json['photo']);
        $mail->send();
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

的config.php

define('DIR_UPLOAD', '/var/www/html/bprod/system/storage/upload/');
define('DIR_UPLOAD_PREV', '/bprod/system/storage/upload/');

发送后我只能查看电子邮件文本。但无法找到附在其中的附件,我可以看到从仪表板上传的图像预览为缩略图。

来自$this->request回复

Request Object
(
    [get] => Array
        (
            [route] => customer/customer/test
            [token] => D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy
        )

[post] => Array
    (
        [CustomerId] => 2
    )

[cookie] => Array
    (
        [_ga] => GA1.1.600216092.1522068686
        [__tawkuuid] => e::localhost::UVxNC635C5um81xpdgZqxi8tzzuktgfU311LCquHb YskASBH9JzZ3BVj0IrqmBf::2
        [currency] => INR
        [language] => en-gb
        [Tawk_55e5bcd36b9188f30fba8e42] => vs13.tawk.to::0
        [PHPSESSID] => 6j1v81a4th5tp99v76f6j1v9bk
        [default] => 3veil82ersfvi23hk0omquude7
    )

[files] => Array
    (
        [file] => Array
            (
                [name] => download.jpeg
                [type] => image/jpeg
                [tmp_name] => /tmp/phpMgJDDZ
                [error] => 0
                [size] => 10681
            )

    )

[server] => Array
    (
        [HTTP_HOST] => localhost
        [HTTP_CONNECTION] => keep-alive
        [CONTENT_LENGTH] => 10966
        [HTTP_ACCEPT] => application/json, text/javascript, */*; q=0.01
        [HTTP_ORIGIN] => http://localhost
        [HTTP_X_REQUESTED_WITH] => XMLHttpRequest
        [HTTP_USER_AGENT] => Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
        [CONTENT_TYPE] => multipart/form-data; boundary=----WebKitFormBoundaryzkfByjwN1qi1LRYb
        [HTTP_DNT] => 1
        [HTTP_REFERER] => http://localhost/bprod/admin/index.php?route=customer/customer/invoice_view&amp;customer_invoice_id=20&amp;customer_id=1042&amp;token=D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy
        [HTTP_ACCEPT_ENCODING] => gzip, deflate, br
        [HTTP_ACCEPT_LANGUAGE] => en,en-GB;q=0.9,en-US;q=0.8
        [HTTP_COOKIE] => _ga=GA1.1.600216092.1522068686; __tawkuuid=e::localhost::UVxNC635C5um81xpdgZqxi8tzzuktgfU311LCquHb+YskASBH9JzZ3BVj0IrqmBf::2; currency=INR; language=en-gb; Tawk_55e5bcd36b9188f30fba8e42=vs13.tawk.to::0; PHPSESSID=6j1v81a4th5tp99v76f6j1v9bk; default=3veil82ersfvi23hk0omquude7
        [PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
        [SERVER_SIGNATURE] => &lt;address&gt;Apache/2.4.18 (Ubuntu) Server at localhost Port 80&lt;/address&gt;

        [SERVER_SOFTWARE] => Apache/2.4.18 (Ubuntu)
        [SERVER_NAME] => localhost
        [SERVER_ADDR] => ::1
        [SERVER_PORT] => 80
        [REMOTE_ADDR] => ::1
        [DOCUMENT_ROOT] => /var/www/html
        [REQUEST_SCHEME] => http
        [CONTEXT_PREFIX] => 
        [CONTEXT_DOCUMENT_ROOT] => /var/www/html
        [SERVER_ADMIN] => webmaster@localhost
        [SCRIPT_FILENAME] => /var/www/html/bprod/admin/index.php
        [REMOTE_PORT] => 47176
        [GATEWAY_INTERFACE] => CGI/1.1
        [SERVER_PROTOCOL] => HTTP/1.1
        [REQUEST_METHOD] => POST
        [QUERY_STRING] => route=customer/customer/test&amp;token=D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy
        [REQUEST_URI] => /bprod/admin/index.php?route=customer/customer/test&amp;token=D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy
        [SCRIPT_NAME] => /bprod/admin/index.php
        [PHP_SELF] => /bprod/admin/index.php
        [REQUEST_TIME_FLOAT] => 1525779741.503
        [REQUEST_TIME] => 1525779741
        [HTTPS] => 
    )

[request] => Array
    (
        [route] => customer/customer/test
        [token] => D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy
        [CustomerId] => 2
    )

)
{"code":"0689ba4829559aa63838037088a207878571336e","success":"Your file was successfully uploaded!","photo":"\/bprod\/system\/storage\/upload\/download.jpeg.v8z19zemLjG6c5ivvAW63R3ohxorIuTw","photo1":"localhost\/\/bprod\/system\/storage\/upload\/download.jpeg.v8z19zemLjG6c5ivvAW63R3ohxorIuTw"}

I had removed the following lines from the .htaccess file from /home/xyz/Desktop/html/bprod/system directory file

<Files *.*>
Order Deny,Allow
Deny from all
</Files> 

Even as I'am facing issue in

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);

而不是将图像从temp移动到/var/www/html/bprod/system/storage/upload。我需要将它移动到config.php下定义的/var/www/html/bprod/admin/upload/目录文件中。但move_uploaded_file()无效。

我不仅需要发送图像文件,还需要发送PDF文件。 我如何克服这种情况?

2 个答案:

答案 0 :(得分:0)

您是否尝试更改代码

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD_PREV . $file);

答案 1 :(得分:0)

由于它没有从URL中获取,因此需要添加一些额外的代码。所以我给出了绝对路径而不是从URL中获取并且没有修改.htaccess文件中的任何内容

所以我改变了

的代码
$mail->AddAttachment($json['photo']);

$mail->AddAttachment(DIR_UPLOAD . $file);

move_uploaded_file()在更改 config.php 中定义的目录文件结构的默认权限后工作,或者您可以通过以下基于debian的OS的命令递归更改整个项目文件结构<终身,

sudo chmod -R 777 bprod/

解决附加任何文件格式的问题(例如:jpeg,pdf,很快......)和move_uploaded_file()工作也很好!