force_download not working in codeigniter after writing - codeigniter

tried to auto download file after file created but its not working. file creating and appending data perfectly but download functionality not working
public function getexportfile(){
$this->load->dbutil();
// $this->load->database('DB_utility','dbutil');
//$this->load->helper('download_helper','download');
$this->load->helper('download_helper');
$this->load->helper('file');
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
## Condition Start
$sWhere = " where condition"; // where conditon
$date = date('Y-m-d');
$filename = 'app/logs/othermarketplace_'.$date.'.csv';
$data = $this->PMP->export($sWhere); // calling model
$result = $this->dbutil->csv_from_result($data);
write_file($filename,$result); // file creating write data perfectly
$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
force_download($filename,$data);
}
anything i missed?

From docs:
// Contents of photo.jpg will be automatically read
force_download('/path/to/photo.jpg', NULL);
//$data = file_get_contents($filename);
//$path = file_get_contents(base_url().$filename);
//$name = "othermarketplace_'.$date.'.csv";
//force_download($nme, $pth);
if (!is_file($filename)) {
exit('No file found.');
}
force_download($filename, NULL);
Note:
These lines might be doing something weird. Perhaps remove them as they aren't being used:
error_reporting(0);
ini_set('display_errors', 0);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

Related

Laravel 5.2 File Upload always (/tmp) saved in DB

I Have my code below, it successfully move the file in the desired path. My problem is that in db it always saved like (/tmp/phpI9zJ1F) with random characters after tmp/. How do I solve this problem?
$quiz = Quiz::findOrFail($id);
$tmp = '';
if( $request->hasFile('survey_image') )
{
$extension = $request->file('survey_image')->getClientOriginalExtension();
do{
$rand = rand(11111,99999);
$imageName = $rand.'.'.$extension;
$tmp = $imageName;
$is_duplicate = Quiz::where('survey_image', $imageName)->count();
}
while( $is_duplicate!=0 );
$request['survey_image'] = (string)$tmp;
$quiz->survey_image_path = 'images/surveys/';
}
$request->file('survey_image')->move(
'images/surveys/' , $tmp);
$quiz->update($request->all());
You would need to use replace() or merge() in order to override the value in $request.
$request->replace(array('survey_image' => (string)$tmp));
You hadn't explained much about it, but I believe that this is a method to only update a image.
So, I would do something like that:
$quiz = Quiz::findOrFail($id);
$tmp = '';
if( $request->hasFile('survey_image') )
{
$extension = $request->file('survey_image')->getClientOriginalExtension();
do{
$rand = rand(11111,99999);
$imageName = $rand.'.'.$extension;
$tmp = $imageName;
$is_duplicate = Quiz::where('survey_image', $imageName)->count();
}
while( $is_duplicate!=0 );
$request['survey_image'] = (string)$tmp;
$quiz->survey_image_path = 'images/surveys/';
$request->file('survey_image')->move(
$quiz->survey_image_path , $tmp);
$quiz->update([
'survey_image' => '/'.$quiz->survey_image_path.$imageName,
]);
}
If you want to reuse your code, you can do something like: (Ps. Code not tested!)
/**
* Handle File Upload
* #param UploadedFile $file [File from request]
* #param string $path [Path where to save the file]
* #param string|boolean $current_file [An old file that you want to delete, before save the new one]
* #return string
*/
public function updateImage(UploadedFile $file, $path, $current_file = false)
{
//Set a random name to the file
$extension = $file->getClientOriginalExtension();
$fileName = str_random(32) . '.' . $extension;
//Delete an old file first
if ($current_file !== false)
if (File::exists($current_file))
File::delete($current_file);
//Move new file to the directory
$file->move($path, $fileName);
return '/'.$path.$imageName;
}
And where you want to save on database:
if( !$request->hasFile('survey_image') ) return false; //Or what you want
$quiz = Quiz::findOrFail($id);
$quiz->update([
'survey_image' => $this->updateImage(request('survey_image'), 'images/surveys/');
]);

Creating a Dynamic PDF and Saving it in a folder using Loop with MYSQL and Codeigniter

This is the public function with looping (Edited)
public function generate_salary_slip(){
$this->load->helper('file');
$this->load->library('m_pdf');
$data = [];
$slip = $this->Admin_Login_Model->generate_salary_slip();
//$html = array();
$html='';
if(!empty($slip)){
foreach($slip as $slip_list){
$id = $slip_list->emp_id;
$data['attendance'] = $this->Admin_Login_Model->get_slip_attendance($id);
$data['emp_profile'] = $this->Admin_Login_Model->get_emp_details($id);
$data['late_day'] = $this->Admin_Login_Model->get_late_days($id);
$data['half_days'] = $this->Admin_Login_Model->get_half_days($id);
$data['salary'] = $this->Admin_Login_Model->get_salary_slip($id);
$data['second_half'] = $this->Admin_Login_Model->get_half_Second_days($id);
//$html=$this->load->view('admin/payslip',$data);
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html .= $this->load->view('admin/payslip', $data, true);
}
$htmlval = $html;
//echo $html;exit;
$this->m_pdf->pdf->WriteHTML($htmlval);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");
$this->session->set_flashdata('success','Salary slips saved in directory!');
redirect('admin_attendance_list');
}else{
$this->session->set_flashdata('message','Salary slips not available for this month!');
redirect('admin_attendance_list');
}
}
File is getting saved in the folder, but Only with the First Record. Also, Repeated loop is getting generated, but with same record.
How to create a HTML by loop.
PS: Using MPDF to generate PDF File
Any hep will be highly appreciated.
You need to take the render, writeHtml and Output calls outside the forech loop, there is you problem.
You could save all the data in a var and then render the HTML as you are doing now and then generate the PDF.
EDIT: Your code should look something like this (please read comments below):
$htmlData = array();
if(!empty($slip)){
foreach ($slip as $slip_list) {
//
$htmlData[] = $data;
}
$pdfFilePath = date("F_Y")."salary_slip.pdf";
$html = $this->load->view('admin/payslip', $htmlData, true);
$this->m_pdf->pdf->WriteHTML($html);
$this->m_pdf->pdf->Output('salary_slips/'.$pdfFilePath, "F");

How to insert values in another table in controller joomla

I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}
Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..

Send params to Joomla module

I write custom module, for example, when module called with parametr 1, module return 1, when called with 2, return 2 e.t.c.
But I cant find any documentation, how to send parametrs from page to module. Its how I call module now:
jimport( 'joomla.application.module.helper' );
$modules = JModuleHelper::getModules('NAME_OF_CUSTOM_POSITION');
$count_array = count($modules);
if ($count_array >0)
{
$attribs['style'] = 'xhtml';
echo JModuleHelper::renderModule( $modules[0], $attribs );
}
?>
But I don't know how to send params nor how to recieve them in my module.
I have used below code in one of my custom component.And it worked for me.
$document = JFactory::getDocument();
$renderer = $document->loadRenderer('module');
$params = array('style'=>'xhtml');
$contents = '';
foreach (JModuleHelper::getModules('NAME_OF_CUSTOM_POSITION') as $mod) {
$registry = new JRegistry();
$registry->loadString($mod->params);
$registry->set('paramname','paramvalue');
$mod->params = (string)$registry;
$contents .= $renderer->render($mod, $params);
}
echo $contents;

Save formatted xml

Hi Can someone please tell me why this inst saving to my XML file? it doesn't return any errors but doesn't write to the file either? It might be silly so I apologize in advance
<?php
$pastor = $_POST["Speaker"];
$title = $_POST["Title"];
$link = $_POST["podcasturl"];
$download = $_POST["Download"];
$podcastid = $_POST["Podcastid"];
$pubdate = $_POST ["Date"];
$filename = 'podcast.xml';
$xml = simplexml_load_file($filename);
$xml->addChild('title');
$xml->addChild('pastor', $pastor);
$xml->addChild('title', $title);
function saveXMLFormatted($xml, $filename) {
$savexml = new DOMDocument('1.0');
$savexml->preserveWhiteSpace = FALSE;
$savexml->loadXML($xml->asXML());
$savexml->formatOutput = TRUE;
file_put_contents($filename, $savexml->saveXML());
}

Resources