How can I refresh the page after force_download in codeigniter controller, here is my controller function. It is not performing any function after calling the force_download.
public function download(){
$this->load->library('user_agent');
$this->load->helper('download');
$file_id = $this->uri->segment(3);
if(!empty($file_id)){
//get file info from database
$fileInfo = $this->Files->get_file($file_id);
foreach ($fileInfo as $key => $object) {
$download_direc = $object->file_direc;
}
//download file
force_download($download_direc, NULL);
//increment the download value by 1 in the db
$this->Files->update_download($file_id);
//refresh the page
redirect($this->agent->referrer());
}
}
Thank you
On the view page when user clicks your anchor link or button to download the file.
Just take the id of that button and put a jQuery interval to 2500-3000 so the page will refresh after 2.5-3 seconds.
you can try this. i hope it will help you.
public function download($fileName = NULL) {
if ($fileName) {
$file = realpath ( "download" ) . "\\" . $fileName;
if (file_exists ( $file )) {
$data = file_get_contents ( $file );
force_download ( $fileName, $data );
} else {
redirect ( base_url () );
}
}
}
Related
Hello there
Hope you will be doing well.I want to redirect to a route after file download but as we know that return only works once in a controller method how i can achieve this with laravel 5.7.I have to set a session and display it when data exported in txt file.I want this with post method.
Every thing is fine but redirect is not working;
Controller Method
public function exportTxtProcess(Request $request)
{
$table = $request->tblExportSelect;
$destinationPath = public_path('/');
$result;
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table . "-" . $today;
$fp = fopen($destinationPath . "$fileName.txt", "wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table, $output);
fwrite($fp, $netResult);
}
$result = fclose($fp);
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$redirect = redirect()->back();
$sess = Session::flash('success', 'Table exported successfully');
return response()->download($pathToFile)->deleteFileAfterSend(true);
}
}
Thank in advance
You can only have 1 response, so it's impossible to instruct a double
return. What you could do, is set the filename you wish to have
downloaded in a session variable, then redirect back to whatever page.
Within the redirected page, you could flash your message, along with
having an automatic download of the file.
Here is some threads on the topic:
How do I redirect after download in Laravel?
PHP generate file for download then redirect
I'm working in WordPress with Contact Form 7. I'm dynamically creating a Word Document based on the users submitted data, and I want to attach that file to the e-mail that the user is sent from Contact Form 7.
To confirm, the file is created and saved in the correct location. My issue is definitely with attaching it to the e-mail from CF7.
I have the following code at the moment:
add_action('wpcf7_before_send_mail', 'cv_word_doc');
function cv_word_doc($WPCF7_ContactForm) {
// Check we're on the CV Writer (212)
if ( $WPCF7_ContactForm->id() === 212 ) {
//Get current form
$wpcf7 = WPCF7_ContactForm::get_current();
// get current SUBMISSION instance
$submission = WPCF7_Submission::get_instance();
if ($submission) {
// get submission data
$data = $submission->get_posted_data();
// nothing's here... do nothing...
if (empty($data))
return;
// collect info to add to word doc, removed for brevity...
// setup upload directory and name the file
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['basedir'] . '/cv/';
$fileName = 'cv-' . str_replace(' ', '-', strtolower($firstName)) . '-' . str_replace(' ', '-', strtolower($lastName)) .'-'. time() .'.docx';
// PHPWord stuff, removed for brevity...
// save the doc
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($upload_dir . $fileName);
// add upload to e-mail
$submission->add_uploaded_file('docx', $upload_dir . $fileName);
// carry on with cf7
return $wpcf7;
}
}
}
Everything works up until $submission->add_uploaded_file('docx', $upload_dir . $fileName);.
There's not much documentation about, but I have read that I need to include something similar to:
add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );
function mycustom_wpcf7_mail_components( $components ) {
$components['attachments'][] = 'full path of your PDF file';
return $components;
}
(source: https://wordpress.stackexchange.com/questions/239579/attaching-a-pdf-to-contact-form-7-e-mail-via-functions-php)
In order to get the attachment to show. However, I don't know how I can get the specific file that I need, as the file is unique to each submission and all of the variables will be in a separate function.
Fixed this issue.
I added:
// make file variable global
global $CV_file;
$CV_file = $upload_dir . $fileName;
after $submission->add_uploaded_file('docx', $upload_dir . $fileName);
Then seperate to the add_action, I used the filter and referenced the global var:
add_filter( 'wpcf7_mail_components', 'mycustom_wpcf7_mail_components' );
function mycustom_wpcf7_mail_components( $components ) {
global $CV_file;
$components['attachments'][] = $CV_file;
return $components;
}
Here is the working solution:
add_filter('wpcf7_mail_components', 'custom_wpcf7_mail_components');
function custom_wpcf7_mail_components($components)
{
//Get current form
$wpcf7 = WPCF7_ContactForm::get_current();
$attachment_file_path = '';
//check the relevant form id
if ($wpcf7->id == '30830') {
// get current SUBMISSION instance
$submission = WPCF7_Submission::get_instance();
if ($submission) {
// get submission data
$data = $submission->get_posted_data();
// setup upload directory
$upload_dir = wp_upload_dir();
if (isset($data['file_name']) && !empty($data['file_name'])) {
/*
* Form hidden attachment file name Ex: 'ProRail_NA_Gen5.pdf'
* You can hard-code the file name or set file name to hidden form field using JavaScript
*/
$file_name = $data['file_name'];
//get upload base dir path Ex: {path}/html/app/uploads
$base_dir = $upload_dir['basedir'];
//file uploaded folder
$file_dir = 'download';
//set attachment full path
$attachment_file_path = $base_dir .'/'.$file_dir.'/'.$file_name;
//append new file to mail attachments
$components['attachments'][] = $attachment_file_path;
}
}
}
return $components;
}
I'll leave a full example using wpcf7_before_send_mail to create and store the PDF and wpcf7_mail_components to attach it to the email.
PDF created with FPDF.
<?php
/**
* Plugin Name: Create and attach PDF to CF7 email
* Author: brasofilo
* Plugin URL: https://stackoverflow.com/q/48189010/
*/
!defined('ABSPATH') && exit;
require_once('fpdf/fpdf.php');
add_action('plugins_loaded', array(SendFormAttachment::get_instance(), 'plugin_setup'));
class SendFormAttachment {
protected static $instance = NULL;
public $formID = 5067; # YOUR ID
public $theFile = false;
public function __construct() { }
public static function get_instance() {
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
public function plugin_setup() {
add_action('wpcf7_before_send_mail', function ( $contact_form, $abort, $submission ) {
if ($contact_form->id() == $this->formID) {
$posted_data = $submission->get_posted_data();
$uploads = wp_upload_dir();
$the_path = $uploads['basedir'] . '/cf7_pdf/';
$fname = $this->createPDF($posted_data, $the_path);
$this->theFile = $the_path . $fname;
}
}, 10, 3);
add_filter( 'wpcf7_mail_components', function( $components ) {
if( $this->theFile )
$components['attachments'][] = $this->theFile;
return $components;
});
}
public function createPDF($posted_data, $savepath) {
$pdf = new FPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',12);
$pdf->SetCreator('example.com');
$pdf->SetAuthor('Author name', true);
$pdf->SetTitle('The title', true);
$pdf->SetSubject('The subject', true);
for($i=1;$i<=40;$i++)
$pdf->Cell(0,10,'Printing line number '.$i,0,1);
$filename = rand() . '_' . time() . '.pdf';
$pdf->Output('F', $savepath . $filename);
return $filename;
}
}
The original code would have worked up until V5.4 where add_uploaded_file was made private.
There is a replacement public function you can use to attach the file with the absolute file path:
$submission->add_extra_attachments( $absolute_file_path );
It may also work with paths relative to the wp_uploads folder.
I have below function to download a pdf file
public function download($id) {
$detail = pesanmakam::findOrFail($id);
$name = date('YmdHis') . ".pdf";
$data = PDF::loadView('guest/log/pdf', compact('detail'))->setPaper('a4')->setWarnings(false)->save('myfile.pdf');
return $data->download($name);
}
above download function works fine but it's just stay on the same page. Is it possible to redirect it to another page after the download succeed?
You can't because forcing download file is made with HTTP header and redirection is based on the same. So you can't do both at the same time.
You can find more information on this other topic here
Read it
public function download($id) {
$detail = pesanmakam::findOrFail($id);
$name = date('YmdHis') . ".pdf";
$data = PDF::loadView('guest/log/pdf', compact('detail'))->setPaper('a4')->setWarnings(false)->save('myfile.pdf');
// return $data->download($name);
return Redirect::to($url);//$url > where u want to go
}
Paste the following line just after the function call
header('Location: http://www.example.com/');
suppose you called function like
$down = download(10);
//then just below it write like
header('Location: http://www.example.com/');
instead of http://www.example.com put the page url where you want to redirect after download.
Try this:
public function download($id) {
$detail = pesanmakam::findOrFail($id);
$name = date('YmdHis') . ".pdf";
$data = PDF::loadView('guest/log/pdf', compact('detail'))->setPaper('a4')->setWarnings(false)->save('myfile.pdf');
$data->save('folder_name/'.$name)
return Redirect::to('url')
}
I have this code which uploads an image from admin and it works well.
add_action('admin_init', 'register_and_build_fields');
function register_and_build_fields() {
register_setting('theme_options', 'theme_options', 'validate_setting', 'delete_file');
}
function validate_setting($theme_options) {
$keys = array_keys($_FILES); $i = 0; foreach ( $_FILES as $image ) {
// if a files was upload
if ($image['size']) {
// if it is an image
if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false);
$options = get_option('theme_options'); echo "<img src='{$options['logo']}' />";
// save the file, and store an array, containing its location in $file
$file = wp_handle_upload( $image, $override ); $theme_options[$keys[$i]] = $file['url']; } else {
// Not an image.
$options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$logo];
// Die and let the user know that they made a mistake.
wp_die('No image was uploaded or invalid format.<br>Supported formats: jpg, jpeg, png, gif.<br> Go <button onclick="history.back()">Back</button> and try again.'); } } // Else, the user didn't upload a file.
// Retain the image that's already on file.
else { $options = get_option('theme_options'); $theme_options[$keys[$i]] = $options[$keys[$i]]; } $i++; }
return $theme_options;
}
and now I want the function to delete the current image.
function delete_file($theme_options) {
if (array_key_exists('delete_file', $_FILES)) {
$image = $_FILES['delete_file'];
if (file_exists($image)) {
unlink($image);
echo 'File '.$image.' has been deleted';
} else {
echo 'Could not delete '.$image.', file does not exist';
}
}
}
I added the button in admin but is doing.. nothing.
I'm building a TemplateOptions in WordPress and now I'm trying to make the logo function to be uploaded and deleted from admin. Like I said, uploading the logo works and now I want to make the field "delete" to work.
I found out that you don't need to insert the record in the DB as you only have a single image and whose name and path are also constant . So you simply need to unlink the image from the directory and it will be deleted, nothing else.
say your logo.png is in your themes's img folder then you should unlink it like this. default is your theme name
$path = ABSPATH.'wp-content/themes/default/img/logo.png';
if(file_exists($path))
{
unlink( $path );
}
Note: Remember that you have to pass the absolute path to the unlink() and not the url having http , because it will give you an error , you can't use http with unlink.
I want to develop an app in php that I can link with a particular photo album in my Facebook profile (or with all my photos) in order to know the direct url link of each photo.
The idea is to make an php script who shows in chronological order my facebook photos like a presentation. Im php programmer, but I know nothing about Facebook integration API. So guys if you can suggest me ways to do this it will be nice. Sorry for my English. Thanks!
here is a class for retriving specific user profile pictures (PHP), you'll get the idea from it to create what you want:
<?php
class FBPicture {
public $uid;
public $dir;
public $type = 'large';
public function setUId ($id) {
$this->uid = $id;
}
public function setDir ($dir) {
$this->dir = $dir;
}
public function fetch ($_uid=null, $_dir=null, $_type=null) {
if ($_uid === null)
throw new CHttpException ('Facebook User ID or Username is not set.');
if ($_dir === null)
$_dir = '/storage/';
if ($_type === null)
$_type = 'large';
$this->uid = $_uid;
$this->dir = $_dir;
$this->type = $_type;
$dir = getcwd () . $this->dir;
$type = $this->type;
// request URI
$host = 'http://graph.facebook.com/' . $_uid;
$request = '/picture';
$type = '?type=' . $type;
$contents = file_get_contents ($host.$request.$type);
// create the file (check existance);
$file = 'fb_' . $uid . '_' . rand (0, 9999);
$ext = '.jpg';
if (file_exists ($dir)) {
if (file_exists ($dir.$file.$ext)) {
$file .= $dir.$file.'2'.$ext;
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
} else {
$file = $dir.$file.$ext;
touch ($file);
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
}
} else {
// false is returned if directory doesn't exist
return false;
}
}
private function appendToFile ($file, $contents) {
$fp = fopen ($file, 'w');
$retVal = fwrite ($fp, $contents);
fclose ($fp);
return $retVal;
}
}
// sample usage:
// $pic will be the filename of the saved file...
$pic = FBPicture::fetch('zuck', 'uploads/', 'large'); // get a large photo of Mark Zuckerberg, and save it in the "uploads/" directory
// this will request the graph url: http://graph.facebook.com/zuck/picture?type=large
?>