I'm having difficulty trying to view a pdf file outside of the webroot folder.
This is the view file - I'm grabbing the file id from the URL and then querying the db to get all the file info stored from the upload.
$fid = $_GET['fid'];
$query = $this->db->query("SELECT * FROM files WHERE FID = $fid");
$fileinfo = $query->result();
foreach ($fileinfo as $row)
{
$fname = $row->file_name;
$ftype = $row->file_type;
$fpath = $row->file_path;
$full_path = $row->full_path;
$raw_name = $row->raw_name;
$client_name = $row->client_name;
$file_ext = $row->file_ext;
$file_size = $row->file_size;
$is_image = $row->is_image;
$width = $row->image_width;
$height = $row->image_height;
$img_type = $row->image_type;
$img_size = $row->image_size_str;
$orig_name = $row->orig_name;
$created = $row->created;
}
Then I'm taking that info and passing it to the File_viewer_model using the following:
$this->load->model('File_viewer_model');
$this->File_viewer_model->getFileInfo($fname,$ftype);
The function in the model that receives the data is as follows:
function getFileInfo($fname,$ftype){
$path = '/home/sitename/uploads/' . $fname;
header('Content-Type: ' . $ftype);
header('Content-Length: ' . filesize($path));
readfile($path);
}
The problem is when I click on the link to open a new tab and try to display the file, I get the following error:
File does not begin with '%PDF-'.
The file is in a 777 permissions directory called uploads right outside of the webroot - I've been all over the web and there seems to be several methods to display a pdf file, none of which seem to work for me. Any help would be appreciated. Thanks!
Solved: The problem was I was passing a header_view page in the controller before the $this->load->view('file_viewer_view'); section.
The PDF viewer was trying to parse the header_view first before the header('Content-Type: application/pdf') code in the file_viewer_view and thus generating the error.
I removed everything from the controller before the $this->load->view('file_viewer_view'); and it works like a champ!
Hopefully, this will save someone several hours of banging your head against the wall like I experienced!
Related
I have a controller which handles the upload functionality of the music file. The controller uses this Laravel getID3 package to parse the metadata from the music file and store in the database.
My code looks like this
if($request->hasfile('songs')){
foreach ( $request->file('songs') as $key => $file){
$track = new getID3($file);
$tifo = $track->extractInfo();
$artistName = $track->getArtist();
$songName = $track->getTitle();
$albumName = $track->getAlbum();
$extension = $track->getFileFormat();
$thumbnail = $track->getArtwork(true);
$thumbnails = 'artwork-'.time().'.'.$thumbnail->getClientOriginalExtension();
$location = time() .uniqid().'.' . $extension;
$file->storeAs('public/songs',$location);
//$file->storeAs('public/sthumbs',$thumbnails);
$file = new MusicUpload();
$music_upload_file = new MusicUpload();
$music_upload_file->user_id = Auth::user()->id;
$music_upload_file->filename = $songName;
$music_upload_file->extension = $extension;
$music_upload_file->artistname = $artistName;
$music_upload_file->albumname = $albumName;
$music_upload_file->location = $location;
$music_upload_file->thumbnail = $thumbnails;
$music_upload_file->save();
}
}
What I want to do is to store both the music file as well as the thumbnail of the file in the database.
Here the $thumbnails will store the image in the specified folder but the image is unreadable, i.e. it has the same file size as the music and doesn't contain the artwork which is to be stored and retrieved.
If I don't include the $thumbnails part, the package default stores to the temp folder which is inaccessible to the controller.
So how do I write the code such that the thumbnail(artwork) of the music gets stored in the correct folder and it can display the output too.
You can store it to storage folder.
Storage::disk('public')->put($location,File::get($file));
Don't forget to run php artisan storage:link
I am trying to build an interface with between my Wordpress page and my practice management software. When I upload files directly to my practice management software a physical copy shows up in the patient file. When browsing files within the software, on first click, I am able to view them in a browser based pdf viewer. If I click again on the file link, the file downloads and opens on my PC's PDF software.
PROBLEM: currently my file uploads to the server and a physical file is placed in the patient file. When browsing files it will not show up in my PDF viewer. It downloads to my PC on the first click and opens into my PDF software. However, the same file, when uploaded directly to the software behaves as expected.
I see no difference in the two files. So I assume there must be a problem with the $contents variable in my query. I am only working with PDF files. To upload attachments in my private messaging software I am using the following code:
function action_getmsgup($uploadid) {
global $wpdb, $out;
$query = $wpdb->prepare("SELECT ID, post_mime_type, guid FROM {$wpdb->prefix}posts WHERE ID = %d", array($uploadid));
$rows = $wpdb->get_results($query, ARRAY_A);
foreach ($rows as $row) {
$url = $row['guid'];
$filename = basename($url);
$path = parse_url($url, PHP_URL_PATH); // just the path part of the URL
$parts = explode('/', $path); // all the components
$parts = array_slice($parts, -6); // the last six
$path = implode('/', $parts);
$filepath = ABSPATH . $path;
// Get file contents and make a blob.
$tmpfile = fopen($filepath, "r");
$contents = fread($tmpfile, filesize($filepath));
$out['filename'] = $filename;
$out['mimetype'] = $row['mimetype'];
$out['contents'] = $contents;
}
}
QUESTION: Is there a problem with my upload method that is not filling $contents correctly?
i have a file with extension PDF and DOCX, and when i download it from my server, the file cannot opened and the size become 1kb, when in my server folder it has 199kb size. iam using database to store the file path and filename, here is my view to download the file
View
<?php echo $details->FILE_NAME; ?>
and my controller
Admin_Controls.php
function download_proposal($id_pemesanan) {
$this->load->helper('download');
$this->load->model('gedung/gedung_model');
$temp_id = substr($id_pemesanan, 7); //i cut the string because it content prefix string
$data = $this->gedung_model->get_proposal_by_id($temp_id);
$path = file_get_contents($data->PATH.$data->FILE_NAME);
$file_name = $data->FILE_NAME;
force_download($file_name, $data);
}
my model
Gedung_Model.php
public function get_proposal_by_id($id_pemesanan) {
$sql = "SELECT * FROM pemesanan_details WHERE ID_PEMESANAN = $id_pemesanan";
$query = $this->db->query($sql);
$hasil = $query->row();
return $hasil;
}
my problem is just after i download the file, it becomes corrupted and cannot open, like i say the size become 1kb. all works well from user click to download until the download process
Thanks in advice
I would like to check the path . You can use absolute path of the file for testing purpose instead of dynamic generated path .
I'm new to yii framework and we have a project in school about uploading and downloading files and I kind of need some assistance...
I followed this link as a sample exactly as it is and it really does upload to the uploads folder in yii but now I'm trying to download it using this code in my view:
$id= $_GET['id'];
$media = Document::model()->findByPk($id);
$path = Yii::app()->basePath . '/../uploads';
$name = $media->doc_file;
Yii::app()->request->sendFile($name, file_get_contents($path."/".$name));
but when it downloads, it wont open because the file format is not supported... any idea how I can
I did a little modification on your code. Pass the id through the url on the view and that will hit the download action inside your controller. You should be good to go with this
public function actionDownload($id)
{
$media = Document::model()->findByPk($id);
$path = Yii::app()->request->baseURL . '/uploads';
$file = $path . '/'.$media->doc_file;
if (file_exists($file)) {
return Yii::app()->getRequest()->sendFile($name, #file_get_contents($path));
}else{
//throw an error here
}
}
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php