Redirect after download file laravel 5.7 - php

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

Related

laravel Can't delete old image when uploaded new image

why my old image can't be deleted when i uploaded new image?
this is my controller where i use to store data and image.
my file image name is stored combination from nama_post_adps and from $imageName where that is query for getClientOriginalName();
public function update(Request $request, Adopsi $adopsi, $id)
{
$getParentJenisHewan = JenisHewan::where("id", $request->jenis_hewan_id)->value("nama_jenis_hewan");
$getParentRasHewan = RasHewan::where("id", $request->ras_hewan_id)->value("nama_ras_hewan");
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$pathstorage = $request->file('image_post_adps')->storeAs('public/post/adopsi',$request->nama_post_adopsi.'-'.$imageName);
$adopsiAttr = $this->validasiRequest();
$adopsiAttr = $request->all();
$adopsiAttr['nama_jenis_hewan'] = $getParentJenisHewan;
$adopsiAttr['nama_ras_hewan'] = $getParentRasHewan;
$adopsiAttr['image_post_adps'] = $imageName;
$adopsiAttr['path-storage'] = $pathstorage;
$adopsiAttr['size'] = $imageSize;
$adopsi = Adopsi::find($id)->update($adopsiAttr);
$delete = Adopsi::find($id);
unlink('app/public/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
// if ($request->file('image_post_adps')) {
// Storage::disk('public')->delete('/post/adopsi/'.$request->nama_post_adopsi.'-'.$request->image_post_adps);
// }
if($adopsi) {
return redirect()->route('adopsi.index')->with('success','Data '.$request->nama_post_adopsi .' telah mendapatkan update terbaru.');
} else {
return redirect()->route('adopsi.index')->with('error','Data gagal'.$request->nama_post_adopsi .'diupdate');
}
}
method above literally same with my store method .
i've try unlink() but it can't work and show error : unlink('post/adopsi/..') no such file or directory , but field can't be updated. then i decided use Storage::disk('public')->delete , field got update, the image change with new but old still same.
You are doing wrong.
First fetch existing data and check if request has file then delete old one then update it
$delete = Adopsi::find($id);
if ($request->file('image_post_adps')) {
Storage::disk('public')->delete('/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
}
$adopsi = Adopsi::find($id)->update($adopsiAttr);

Looking for Laravel php developer to resolve updating function with image uploading its not working

It's my update function and it's not showing image when I echo $fileName. It's not working like it was I want to make it with the condition if there is any image then update that image otherwise leave that I tried many times but it's not working.
public function update(Request $request, Header $header)
{
if($request->hasFile('headerimg')){
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Packages Edited Successfully');
}
I guess that your problem is in your view.
Maybe you forget to use enctype="multipart/form-data" or your input name does not match with mapped controller variable.
For find the exact problem use dd($request) and dd($request->file('headerimg')) and see can you get request correct or not.
I use this code edit image and if image was not selected the old image will remain same without any error.
public function update(Request $request, Header $header)
{
$file = $request->headerimg;
$id = $request->id;
if($file == ''){
$arr['header'] = Header::select()->where($id);
$fileName = $header['headerimg'];
}
else{
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Page Edited Successfully');
}

How to redirect after download?

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')
}

how to check and delete if file uploaded before with codeigniter

i build function to upload zip files but when user upload file two times it didnt delete the first uploaded file but added increment number to the file name (( file.zip,file1.zip,file2.zip,,,etc )
so i want to tell the function when the user uploaded the same file name delete the first file and upload this second file or replace it ... anyone help me how to do that...
/**
* change book source file
*
* #param integer $book_id
*/
public function upload_book_zip($book_id) {
$vars = array();
$vars['upload_path'] = PUBPATH . 'global/modules/bookstore/files/books_source_file/';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
$book = $this->d_book->find_by_id($book_id);
if (isset($_POST['submit'])) {
$file_name = $this->upload($vars);
if ($file_name === NULL) { // error happens while uploading file
$vars['upload_errors'] = $this->upload->display_errors("<p class='notification n-error'>", "</p>");
} else {
$this->d_book->update_one_field($book_id, 'bo_path_zip', $file_name);
$this->session->set_flashdata('success_msg', lang('file_uploaded'));
redirect('bookstore/admin_d_book/');
}
} else {
$vars['upload_errors'] = NULL;
}
if ($book->bo_path_zip) { // load cover image
$vars['file_path'] = base_url() . 'global/modules/bookstore/files/books_source_file/' . $book->bo_path_zip;
} else {
$vars['file_path'] = NULL;
}
$vars['controller_name'] = 'admin_d_book';
$this->view('bookstore/admin/change_zip_file', $vars);
}
/**
*
* #param array $config the configuration array
* #return string
*
*/
private function upload($config) {
$this->load->library('upload', $config);
if (!$this->upload->do_upload("file")) {
return $uploadData['file_name'] = NULL;
} else {
$uploadData = $this->upload->data();
log_message('debug', 'file has been uploaded ok - file name is ' . $uploadData['file_name']);
return $uploadData['file_name'];
}
}
you can do that by adding
$vars['overwrite'] = TRUE;
better check File upload library
Set overwrite to true in the config array you pass
$vars = array();
$vars['upload_path'] = 'filepath here';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
// add this line
$vars['overwrite'] = true;
// the old file will now get overwritten
$file_name = $this->upload($vars)
A better method is to check the md5 or sha1 checksum of the file.
If two users uploads two different files with the same name to the server, the file on server will be overwritten and it is impossible to distingush the file by just name.
Also, it can be done easily in PHP.

Retrieving Facebook photos from a php script

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
?>

Categories