After logging into admin dashboard and clicking upload image it need's to upload an image file as well as it should send that particular image via e-mail as an attachment. Both occurs simultaneously.
But here I could merely save this image to oc_upload table. But I couldn't able to send that particular image as an attached file via e-mail and here is my following code.
<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));
}
define('DIR_UPLOAD', '/var/www/html/bprod/system/storage/upload/');
define('DIR_UPLOAD_PREV', '/bprod/system/storage/upload/');
After sending I could only view the email text. But unable to find attachment enclosed in it and I could see the preview of the image uploaded from dashboard as a thumbnail.
From the $this->request
response
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&customer_invoice_id=20&customer_id=1042&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] => <address>Apache/2.4.18 (Ubuntu) Server at localhost Port 80</address> [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&token=D4Xw7yHMrwZ3ajuIBa6HfzTkFXXOBMuy [REQUEST_URI] => /bprod/admin/index.php?route=customer/customer/test&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);
Instead of moving the image from temp to /var/www/html/bprod/system/storage/upload
. I need to move it into /var/www/html/bprod/admin/upload/
directory file defined under config.php. But move_uploaded_file()
doesn't work.
I need to send not only image files, but PDF files also. How do I overcome this situation?
Since it was not fetching from the URL, it need's to add some extra code to do. So I gave the absolute path instead of fetching from the URL and didn't modified anything from the .htaccess file
So I changed the code from
$mail->AddAttachment($json['photo']);
to
$mail->AddAttachment(DIR_UPLOAD . $file);
move_uploaded_file()
worked, after changing the default permission of directory file structure defined in config.php or you could change the entire projects files structure recursively by the below command on debian based OS in the terminal, as
sudo chmod -R 777 bprod/
That solve's the issue for attaching any file formats (Eg.: jpeg, pdf, and soon...) and move_uploaded_file()
work's fine as well!