I use Imagick to count the number of pages in my PDF which is uploaded by the client except that my var_dump does not return any results.
Here is my prestashop code from my ProductController.php controller for uploading files.
class ProductController extends ProductControllerCore
{
const CUSTOMIZATION_FILE_DIR = 'customizations';
protected function pictureUpload()
{
if (!($field_ids = $this->product->getCustomizationFieldIds()))
return false;
$authorized_file_fields = array();
foreach ($field_ids AS $field_id)
{
if ($field_id['type'] == Product::CUSTOMIZE_FILE)
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file' . (int)$field_id['id_customization_field'];
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES AS $field_name => $file)
{
if (in_array($field_name, $authorized_file_fields) AND isset($file['tmp_name']) AND !empty($file['tmp_name']))
{
// If there is an upload error, let the parent handle it
if ($file['error'] != UPLOAD_ERR_OK)
continue;
// If the file is not allowed, let the parent handle it
if (!$this->isUploadTypeAllowed($file))
continue;
// Unset the PDF to prevent the parent to handle this file
unset($_FILES[$field_name]);
// Create dir
mkdir(_PS_UPLOAD_DIR_ . ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id, 0777, true);
// Mark the file as a custom upload
$file_name = ProductController::CUSTOMIZATION_FILE_DIR.'/'.$this->context->cart->id.'/P'. md5(uniqid(rand(), true)).'.pdf';
$doc = exec("identify -format %n $file_name");
var_dump($doc);
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!move_uploaded_file($file['tmp_name'], $tmp_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Copy file to the upload dir
if (!copy($tmp_name, _PS_UPLOAD_DIR_.$file_name))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Chmod the new file
if (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777))
{
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Create a fake thumb to avoid error on delete, this hack avoids lots of core method override
file_put_contents(_PS_UPLOAD_DIR_ . $file_name . '_small', '');
chmod(_PS_UPLOAD_DIR_ . $file_name . '_small', 0777);
// Register the file
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
// Remove tmp file
unlink($tmp_name);
}
}
return parent::pictureUpload();
}
protected function isUploadTypeAllowed($file)
{
/* Detect mime content type */
$mime_type = false;
$types = array('application/pdf', 'application/zip'); // Extra mime types can be added here
if (function_exists('finfo_open'))
{
$finfo = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
}
elseif (function_exists('mime_content_type'))
{
$mime_type = mime_content_type($file['tmp_name']);
}
elseif (function_exists('exec'))
{
$mime_type = trim(exec('file -b --mime-type '.escapeshellarg($file['tmp_name'])));
}
if (empty($mime_type) || $mime_type == 'regular file')
{
$mime_type = $file['type'];
}
if (($pos = strpos($mime_type, ';')) !== false)
$mime_type = substr($mime_type, 0, $pos);
// is it allowed?
return $mime_type && in_array($mime_type, $types);
}
}
Thank you.
Related
I am developing a module for my client to upload and browse file in Opencart.
when I am uploading file from my back-end server I am getting the output as file.zip.xyzasdf. Where I just want to remove this .xyzasdf
Can any one suggest me how to remove sanitize from the following code...
public function upload() {
$this->load->language('catalog/download');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'catalog/download')) {
$json['error'] = $this->language->get('error_permission');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}
// 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'] = $this->language->get('error_filetype');
}
// 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'] = $this->language->get('error_filetype');
}
// 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'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
$file = $filename . '.' . token(32);
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_FOLDER . $file);
$json['filename'] = $file;
$json['mask'] = $filename;
$json['success'] = $this->language->get('text_upload');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Any help would be greatly appreciated...
Thanks
Removing the random string that is added to the filename is simple. Just change
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $file);
to:
move_uploaded_file($this->request->files['file']['tmp_name'], DIR_UPLOAD . $filename);
But keep in mind that this will bring problems.
OpenCart saves the random string in the database at the time of file upload, so it will later use it to identify the file.
If you delete this feature, the uploaded files in the admin panel will not be available.
How to create Zip archive for file only particular extension in my case .TIF .JPG .TXT
currently i have added single extensions in code you can modify it later on.
<?php
/* creates a compressed zip file */
function create_zip($files = array(), $destination = '', $overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return false;
}
//vars
$valid_files = array();
//if files were passed in...
if (is_array($files)) {
//cycle through each file
foreach ($files as $file) {
//make sure the file exists
if (file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if (count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach ($valid_files as $file) {
$zip->addFile($file, $file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
} else {
return false;
}
}
//your directory path where all files are stored
$dir = 'D:\xampp\htdocs\samples\zip';
$files1 = scandir($dir, 1);
// $ext = "png"; //whatever extensions which you want to be in zip.
$ext = ['jpg','tif','TXT']; //whatever extensions which you want to be in zip.
$finalArray = array();
foreach ($files1 as $key => $value) {
$getExt = explode(".", $value);
if ( in_array($getExt[1] , $ext) ) {
$finalArray[$key] = $value;
}
}
$result = create_zip($finalArray, 'my-archive' . time() . '.zip');
if ($result) {
echo "Operation done.";
}
?>
i think this is what you want.
let me know if you have any issue.
I have override the ProductController.php controller so that the customer can integrate a PDF into his order.
protected function pictureUpload()
{
if (!($field_ids = $this->product->getCustomizationFieldIds()))
return false;
$authorized_file_fields = array();
foreach ($field_ids AS $field_id) {
if ($field_id['type'] == Product::CUSTOMIZE_FILE)
$authorized_file_fields[(int)$field_id['id_customization_field']] = 'file' . (int)$field_id['id_customization_field'];
}
$indexes = array_flip($authorized_file_fields);
foreach ($_FILES AS $field_name => $file_doc) {
if (in_array($field_name, $authorized_file_fields) AND isset($file_doc['tmp_name']) AND !empty($file_doc['tmp_name'])) {
/*if ($_POST[$field_name.'_filename'] != '' ) {
$testName = $_POST[$field_name . '_filename'];
} else if (isset($_FILES[$field_name]['name'])){
$testName = $_FILES[$field_name]['name'];
} else if ($_FILES['file5'['name']] != ''){
$testName = 'totop';
}*/
// If there is an upload error, let the parent handle it
if ($file_doc['error'] != UPLOAD_ERR_OK)
continue;
// If the file is not allowed, let the parent handle it
if (!$this->isUploadTypeAllowed($file_doc))
continue;
// Unset the PDF to prevent the parent to handle this file
unset($_FILES[$field_name]);
// Create dir
mkdir(_PS_UPLOAD_DIR_ . ProductController::CUSTOMIZATION_FILE_DIR . '/' . $this->context->cart->id, 0777, true);
// Mark the file as a custom upload
$file_name = ProductController::CUSTOMIZATION_FILE_DIR . '/' . $this->context->cart->id . '/P' . md5(uniqid(rand(), true)) . '.pdf';
$tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
if (!move_uploaded_file($file_doc['tmp_name'], $tmp_name)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Copy file to the upload dir
if (!copy($tmp_name, _PS_UPLOAD_DIR_ . $file_name)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Chmod the new file
if (!chmod(_PS_UPLOAD_DIR_ . $file_name, 0777)) {
$this->errors[] = Tools::displayError('An error occurred during the PDF upload.');
return false;
}
// Create a fake thumb to avoid error on delete, this hack avoids lots of core method override
file_put_contents(_PS_UPLOAD_DIR_ . $file_name . '_small', '');
chmod(_PS_UPLOAD_DIR_ . $file_name . '_small', 0777);
// Register the file
$this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
// Parsing file
exec('/usr/bin/pdfinfo ' . _PS_UPLOAD_DIR_ . $file_name, $output);
$arrayValue = preg_grep('/\b(Pages)\b/i', $output);
$arrayKey = count($arrayValue) > 0 ? key($arrayValue) : false;
// Size file
$fileSize = fileSize(_PS_UPLOAD_DIR_ . $file_name);
// Name file
$nameFile = explode(".", $file_doc['name']);
$this->context->smarty->assign('customizationParsingFile', (int)substr($arrayValue[$arrayKey], -5));
$this->context->smarty->assign('customizationFileSize', $this->fileSizeUpload($fileSize));
$this->context->smarty->assign('customizationNameFile', $nameFile[0]);
// Remove tmp file
unlink($tmp_name);
}
}
return parent::pictureUpload();
}
I would like this PDF to be associated with the client. Do you have any idea how I could do that?
Thank you.
In Admin Order page you can get Cart ID associated with current Order.
Customization is associated with Cart ID (check Customization.php).
So from Cart ID you can get your Customization and the PDF of that customer.
hello Friends i am using the jquery file upload plugin to upload the files.when i upload the any file then it moves into a folder successfully and also file info into database.
but now i want to response back after successfully insertion into database.
And i also have always an error that is:Error SyntaxError: Unexpected token <
the image of error look like this:
and here is the function in which i am performing database insert query and moving image into folder.
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
GLOBAL $con;
$time=time();
$folder_path="../../uploads/media/";
$rand=rand();
$user_id=$_SESSION['id'];
$file = new stdClass();
$file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
$index, $content_range);
$file->size = $this->fix_integer_overflow(intval($size));
$file->type = $type;
if ($this->validate($uploaded_file, $file, $error, $index)) {
$this->handle_form_data($file, $index);
$upload_dir = $this->get_upload_path();
if (!is_dir($upload_dir)) {
mkdir($upload_dir, $this->options['mkdir_mode'], true);
}
$file_path = $this->get_upload_path($file->name);
$append_file = $content_range && is_file($file_path) &&
$file->size > $this->get_file_size($file_path);
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
if ($append_file) {
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
//move_uploaded_file($uploaded_file, $file_path);
////
$filename = date('YmdHis',$rand).$_SESSION['id'].$name;
$file_size=$size;
$file_size=$file_size/1000;
move_uploaded_file($uploaded_file,$folder_path.$filename);
mysqli_query($con,"insert into gallery(login_id,pic,timestamp,file_size,status)values('$user_id','$filename','$time','$file_size','1')");
$gallery_id=mysqli_insert_id($con);
////
}
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path,
fopen('php://input', 'r'),
$append_file ? FILE_APPEND : 0
);
}
$file_size = $this->get_file_size($file_path, $append_file);
if ($file_size === $file->size) {
$file->url = $this->get_download_url($file->name);
if ($this->is_valid_image_file($file_path)) {
$this->handle_image_file($file_path, $file);
}
} else {
$file->size = $file_size;
if (!$content_range && $this->options['discard_aborted_uploads']) {
unlink($file_path);
$file->error = $this->get_error_message('abort');
}
}
$this->set_additional_file_properties($file);
}
return $file;
}
now from the above function i want the response gallery_id
how can i remove this error and get response after the successfull file upload.
You are the genious people please help me and ask if something not clear.
I wrote the following php function to upload files but I'm having a hard time with the array of allowed file types. If I assign just one file type i.e. image/png, it works fine. If I assign more than one, its not working. I use the in_array() function to determine the allowed file types but I can't figure out how to use it properly.
Thank you!
function mcSingleFileUpload($mcUpFileName, $mcAllowedFileTypes, $mcFileSizeMax){
if(!empty($mcUpFileName)){
$mcIsValidUpload = true;
// upload directory
$mcUploadDir = UPLOAD_DIRECTORY;
// current file properties
$mcFileName = $_FILES[$mcUpFileName]['name'];
$mcFileType = $_FILES[$mcUpFileName]['type'];
$mcFileSize = $_FILES[$mcUpFileName]['size'];
$mcTempFileName = $_FILES[$mcUpFileName]['tmp_name'];
$mcFileError = $_FILES[$mcUpFileName]['error'];
// file size limit
$mcFileSizeLimit = $mcFileSizeMax;
// convert bytes to kilobytes
$mcBytesInKb = 1024;
$mcFileSizeKb = round($mcFileSize / $mcBytesInKb, 2);
// create array for allowed file types
$mcAllowedFTypes = array($mcAllowedFileTypes);
// create unique file name
$mcUniqueFileName = date('m-d-Y').'-'.time().'-'.$mcFileName;
// if file error
if($mcFileError > 0)
{
$mcIsValidUpload = false;
mcResponseMessage(true, 'File error!');
}
// if no file error
if($mcFileError == 0)
{
// check file type
if( !in_array($mcFileType, $mcAllowedFTypes) ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'Invalid file type!');
}
// check file size
if( $mcFileSize > $mcFileSizeLimit ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'File exceeds maximum limit of '.$mcFileSizeKb.'kB');
}
// move uploaded file to assigned directory
if($mcIsValidUpload == true){
if(move_uploaded_file($mcTempFileName, $mcUploadDir.$mcUniqueFileName)){
mcResponseMessage(false, 'File uploaded successfully!');
}
else{
mcResponseMessage(true, 'File could not be uploaded!');
}
}
}
}
}
//mcRequiredFile('mcFileUpSingle','please select a file to upload!');
mcSingleFileUpload('mcFileUpSingle', 'image/png,image/jpg', 2097152);
Change this line:
$mcAllowedFTypes = array($mcAllowedFileTypes);
To this:
$mcAllowedFTypes = explode(',',$mcAllowedFileTypes);
Don't rely on the clent file type from $_FILES which is unsafe, get it from the file content.
Then define your allowed file types, check if the upload file type in your white list.
if(in_array(mime_type($file_path),$allowed_mime_types)){
// save the file
}
$allowed_mime_types = array(
'image/jpeg',
'image/jpg',
'image/png',
'image/gif',
'video/mp4'
);
/*
For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.
For PHP<5.3.0, you can use your's system's `file` command to get the file information.
*/
function mime_type($file_path)
{
if (function_exists('finfo_open')) {
$finfo = new finfo(FILEINFO_MIME_TYPE, null);
$mime_type = $finfo->file($file_path);
}
if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
if ($return > 0) {
ob_end_clean();
$mime_type = null;
}
$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
$mime_type = null;
}
$mime_type = $match[1];
}
return $mime_type;
}