Unale to save runtime generated file to directory - php

I have one form. When user submit the form, I will store the data on database and generate the pdf of the same. Here what I want to do is:
Download PDF file;
Save the PDF in a folder.
Downloading the PDF is working perfectly, but it is not being saved in a folder.
public function get_pdf() {
$count = 1;
for ($i = 0; $i < count($_POST['description']); $i++) {
$table_data[] = array(
'serial' => $count,
'description' => $_POST['description'][$i],
'unit' => $_POST['unit'][$i],
'quantity' => $_POST['quantity'][$i],
'rate' => $_POST['rate'][$i],
'amount' => $_POST['amount'][$i]
);
$count++;
}
if (!empty($table_data)) {
// loading pdf library //
$this->load->library('cezpdf');
// field names //
$table_data_field = array(
'serial' => 'S.No.',
'description' => 'Work Description',
'unit' => 'Unit',
'quantity' => 'Quantity',
'rate' => 'Rate',
'amount' => 'Amount'
);
$this->cezpdf->ezTable($table_data, $table_data_field, 'Quotation', array('width' => 500, 'justification' => 'center'));
ob_start();
$this->cezpdf->ezStream();
$data = ob_get_contents();
ob_end_clean();
// save the quotation file on client folder //
move_uploaded_file('Quotation', FCPATH . '/quotation/' . $data);
// force to download the file //
$this->load->helper('download');
force_download('Quotation.pdf', $data);
}
}
Please help me on this. I use CodeIgniter.

Firstly, I don't think you ought to be using move_uploaded_file, and secondly, the name of your file contains the contents of the PDF, not a filename.

Related

Call to a member function getSize() on null

I have a problem uploading a file can you help me? when I upload a smaller file it runs smoothly but when I upload a larger file it's problematic, does anyone know the solution? this is the controller part:
$title = $this->request->getPost('title');
$kategori = $this->request->getPost('kategori');
$seo = str_replace(" ", "-", strtolower($kategori));
$deskripsi = $this->request->getPost('deskripsi');
$data=array();
$file = $this->request->getFile('imagefile');
$data=array();
if ($file->getSize() > 0){
$image=$file->getRandomName();
$file->move('./uploads/peta/',$image);
$data = array(
'title' => $title,
'kategori' => $kategori,
'seo' => $seo,
'deskripsi' => $deskripsi,
'file' => $image
);
}else{
$data = array(
'title' => $title,
'kategori' => $kategori,
'seo' => $seo,
'deskripsi' => $deskripsi
);
}
Use $files->hasFile('') to check whether file exist. And then check other file properties as mentioned below.
$files = $this->request->getFiles();
if ($files->hasFile('imagefile'))
{
$file = $files->getFile('imagefile');
// Generate a new secure name
$name = $file->getRandomName();
// Move the file to it's new home
$file->move('/path/to/dir', $name);
echo $file->getSize(); // 1.23
echo $file->getExtension(); // jpg
echo $file->getType(); // image/jpg
}
You need to check if the file is set before trying to call file methods. It seems that the file isn't being sent over your request. As you said, it works with smaller files so please check the php.ini file to see your max_upload_size settings and post_max_size settings. Change the maximum upload file size
Otherwise, to ensure your code won't fail on posts, you can do this:
if (!empty($file) && $file->getSize() > 0){
$image=$file->getRandomName();
$file->move('./uploads/peta/',$image);
$data = array(
'title' => $title,
'kategori' => $kategori,
'seo' => $seo,
'deskripsi' => $deskripsi,
'file' => $image
);
}else{
$data = array(
'title' => $title,
'kategori' => $kategori,
'seo' => $seo,
'deskripsi' => $deskripsi
);
}
This will check if there is a file before trying to use it.

Upload CSV File in Admin Controller - Custom module

I'm trying to create an Admin Controller with a csv file uploader to process it like an array.
I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.
Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.
I need to create multiple object of different classes that I made, thanks to the csv file.
Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)
Waiting for your help guys !
Update :
Update :
Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?
Here is my code :
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_BULB_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_BULB_DATA'
),
),
'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
),
);
if(isset($_FILES['DB_BULB_DATA'])){
$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
print_r($headers);
}
}
There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.
Just find out how to do it, I feel dummy 😅
I just needed to save my tmp file as a csv to be able to use it then.
Here is the full code :
<?php
class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_<YourThings>_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_<YourThings>_DATA'
),
),
'submit' => array('title' => $this->l('Save')),
),
);
}
public function initContent()
{
parent::initContent();
unset($_FILES);
}
public function postProcess()
{
$fileName = '<YourThings>Db.csv';
if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
if (isset($_FILES['DB_<YourThings>_DATA'])) {
$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
} else {
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
unset($_FILES['DB_<YourThings>_DATA']);
}
}

Yii2 send pdf to mail not working?

I am using kartik mpdf extension to generate using the mention below code it work and show the pdf in next tab
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
return $pdf->render();
Now for send the generatd pdf on mail i want to send the mail before save it on server using below code
$content = $pdf->content;
$filename = $pdf->filename;
$sendemail=Yii::$app->mail->compose()
->attachContent($content, [
'fileName' => $filename,
'contentType' => 'application/pdf'
])
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
Try my best to hit api and generate pdf but this also doesnt work.
$mpdf = $pdf->getApi();
$mpdf->WriteHTML($content);
$path = $mpdf->Output(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf', 'F');
It also retrn Null
First i have save the generated pdf in the server directory and then send it to mail and unlink after sending succcessfully using the below code
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
if($mail){
$content = $pdf->content;
$filename = $pdf->filename;
// $mpdf = $pdf->getApi();
// $mpdf->WriteHtml($content);
$path = $pdf->Output($content,Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf',\Mpdf\Output\Destination::FILE);
$sendemail=Yii::$app->mail->compose()
->attach(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf')
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
if($sendemail)
{
unlink(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf');
return $this->render('mailed');
}
I cant find where the exact error is but I had successfully generated pdf via mpdf with
$model= $this->findModel($id);
// get your HTML raw content without any layouts or scripts
$content = $this->renderPartial('print_salaryslip',['model'=>$model]);
// setup kartik\mpdf\Pdf component
$pdf = new Pdf([
// set to use core fonts only
'mode' => Pdf::MODE_BLANK,
// A4 paper format
'format' => Pdf::FORMAT_A4,
// portrait orientation
'orientation' => Pdf::ORIENT_PORTRAIT,
// stream to browser inline
'destination' => Pdf::DEST_BROWSER,
// your html content input
'content' => $content,
// format content from your own css file if needed or use the
// enhanced bootstrap css built by Krajee for mPDF formatting
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Krajee Report Title'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>[' PAYSLIP'],
'SetFooter'=>['{PAGENO}'],
]
]);
// return the pdf output as per the destination setting
return $pdf->render();
and make sure the$contentis pure html.
Do something like this
...
if (!empty($id)) {
$emailSend = Yii::$app->mailer->compose(['html' =>'My-template-html'],[
'email' => $receiver->email,
'name' => $receiver->name
])
->setFrom(["info#mail.com"])
->setTo($email)
->setSubject($subject)
->attach(Yii::getAlias('#backend').'/web/uploads/pdf/'.'Certificate'.'.pdf');
return $emailSend->send();
Yii::$app->session->setFlash('success', 'Email Sent Successfully');
}
...

Can't write image data laravel 5 Intervention

This question have been asked many times in SO, but still I cannot figure it out why is this not working for me.
I am working on E-Commerce Laravel Project.
The issue is that, when the admin uploads the image file of the product, get the error of:
Can't write image data to path
(http://example.com/ankur/images/uploads/products/img-newprod-540-350-350.jpg)
Here's the controller snippet of storing the image and related entries:
public function storeGeneral(Request $request)
{
$this->validate($request, [
'code' => 'required|alpha_dash|unique:products',
'name' => 'required',
'description' => 'string',
'details' => 'string',
'price' => 'required|regex:/^\d*(\.\d{2})?$/',
'tax_amount' => 'required|regex:/^\d*(\.\d{2})?$/',
'net_price' => 'required|regex:/^\d*(\.\d{2})?$/',
'weight' => 'required|integer',
'image_file' => 'image|mimes:jpeg,jpg,JPG'
]);
if ($request->ajax() ) {
if ($request->file('image_file' ) ) {
$request['img_code'] = 'img-' . $request->get('code' );
$product = Product::create($request->all() );
$product->categories()->attach($request->input('category_id') );
Session::put('product_last_inserted_id', $product->id);
$mgCode = DB::table('products')->latest()->limit(1)->pluck('img_code');
$imageType = [
'product' => [
'height' => 350,
'width' => 350
],
'carousel' => [
'height' => 163,
'width' => 163
],
'cart' => [
'height' => 64,
'width' => 64
]
];
foreach($imageType as $key => $value)
{
$fileName = Safeurl::make($mgCode );
$image = Image::make($request->file('image_file' ) );
//$path = public_path( 'images/uploads/products/' );
$path = url('/images/uploads/products/');
if ($key == 'product') {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
} else if ($key == 'carousel' ) {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
} else if ($key == 'cart' ) {
$image->resize($value['width'], $value['height'] );
$image->save($path.'/'.$fileName."-". $value['width'] ."-".$value['height'] .".jpg", 100 );
}
}
} else {
$product = Product::create($request->all() );
Session::put('product_last_inserted_id', $product->id);
}
return response(['status' => 'success', 'msg' => 'The product has been added successfully.']);
}
return response(['status' => 'failed', 'msg' => 'The product could not be added successfully.']);
}
The folder permission that I have is 0777 for the images directory and it's sub directories.
But still I get the above mentioned error exception.
EDIT 1:
This is the folder structure in my hosting account file manager which is inside the public_html directory:
Can anybody help me out with this.
Thanks in advance.
I have somehow figured it out.
Instead of using url() or base_path(), I used public_path().
Code that I used:
$path = public_path('../../public_html/ankur/images/uploads/products');
Worked like a charm.
You are trying to save image using url. Instead of url try following
$path = base_path().'/images/uploads/products';
You can not save the image using http path. You have to use base_path() or manual type full server directory path /home/webtuningtechnology/public_html/images/ like this

How to code multiple file upload using CodeIgniter?

I want to have a multiple file upload code.
For example:
Koala.jpg
Penguins.jpg
Jellyfish.jpg
There is input text where the user can set the new name of the image.
The user will now upload the images and the inputted text for new image name is "Animals"
Now, what I want is when this uploaded the output should be Animals1.jpg, Animals2.jpg, Animals3.jpg.
The problem is when I tried to upload all these images, only one image is uploading.
I tried to make research and applied some codes on my program, but still not working.
Controller
public function do_upload() {
$config = array(
'image_library' => 'gd2',
'file_name' => $this->input->post('finame'),
'upload_path' => './public/img/uploads',
'upload_url' => base_url().'public/img/uploads',
'allowed_types' => 'gif|jpg|jpeg',
'max_size' => '1024KB',
'max_width' => '1024',
'max_height' => '768',
'maintain_ratio'=> TRUE,
'overwrite' => false,
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error_msg = "<div class='alert alert-error'>".$this->upload->display_errors()."</div>";
$error = array('error' => $error_msg);
}
else {
$upload_data = $this->upload->data();
$data['thumbnail_name'] = $upload_data['raw_name']. '_thumb' .$upload_data['file_ext'];
$file_array = array(
'image' => $data['thumbnail_name'],
'image_name' => $upload_data['file_name'],
//'description' => "",
'date_created' => date('Y-m-d H:i:s', now()),
'date_modified' => date('Y-m-d H:i:s', now()),
'author' => $this->session->userdata('username'),
'size' => $upload_data['file_size'],
'type' => $upload_data['image_type'],
'width' => $upload_data['image_width'],
'height' => $upload_data['image_height'],
//'document_name' => $field,
//'department' => $field2,
//'notes' => "",
);
$this->session->set_userdata('image_print', $file_array);
$this->load->database();
$this->db->insert('tbl_image', $file_array);
$data = array('upload_data' => $this->upload->data());
$user_level['records']=$this->user_model->get_records();
$this->load->view('v_dashboard/page/header_view', $user_level);
$this->load->view('v_document/upload/upload_result_view', $data);
$this->load->view('v_dashboard/page/footer_view');
}
}
I have this on my HTML
<label for="file"><strong>Select File To Upload:</strong></label>
<input type="file" name="userfile[]" multiple class="btn transcolor btn-file"/>
<br/><br/>
By the way, I'm using BLOB on my database.
I tried to refer to this links
Ellislab
GitHub
StackOverflow
StackOverflow
CodingLikeASir
You have to run the for loop till the count of the uploaded image file.
Like this:
for ($i=0; $i < count($_FILES['userfile']['name']); $i++)
{
// function to add the image name one by one into database.
}

Categories