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
}
}
Related
I just started moving CodeIgniter 3 project to CodeIgniter 4.
Everything works fine except file upload.
I would like to keep the user uploaded files in /writable/uploads. Below is the code I use to move the uploaded file to desired location.
$target_dir = '/writable/uploads/recordings/';
$target_file = $target_dir . basename($_FILES["gfile"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
if($FileType != "mp3") {
$vmuploadOk = 1;
}
else
$vmuploadOk = 1;
if ($vmuploadOk == 1) {
$greetfile = $id . "g" . basename($_FILES["gfile"]["name"]);
$target_filenew = $target_dir . $greetfile;
move_uploaded_file($_FILES["gfile"]["tmp_name"], $target_filenew);
}
I assume that it is because CI4 keeps writable folder outside public folder.
You are not using CodeIgniter's built in functions. Everything shown in your code are PHP functions. If you want to leverage built in CI functions, then look through the documentation as linked by #Boominathan Elango.
To get the file from the request:
$file = $this->request->getFile('here_goes_input_name');
As specified here
To move the file using CI function:
$file->move(WRITEPATH.'uploads', $newName);
As specified here
This worked for me and I hope it will also work for you. In codeigniter 4 please use this to upload your files and move it in your controller.
if($imagefile = $this->request->getFiles())
{
if($img = $imagefile['gfile'])
{
if ($img->isValid() && ! $img->hasMoved())
{
$newName = $img->getRandomName(); //This is if you want to change the file name to encrypted name
$img->move(WRITEPATH.'uploads', $newName);
// You can continue here to write a code to save the name to database
// db_connect() or model format
}
}
}
OR
if($img = $this->request->getFile('gfile'))
{
if ($img->isValid() && ! $img->hasMoved())
{
$newName = $img->getRandomName();
$img->move(ROOTPATH . 'public/uploads/images/users', $newName);
// You can continue here to write a code to save the name to database
// db_connect() or model format
}
}
Then in your html input field
<input type="file" name="gfile">
I hope this works else call my attention
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 want to delete my pdf file from server. my controller function looks like
function delete_pdf()
{
$id = (isset($_GET['id']) && $_GET['id']!='')?$_GET['id']:'1';
$user_email = $this->session->userdata('user_email');
$file = site_url('pdf files/'.$user_email.'/pdf #'. $id.'.pdf');
unlink($file);
}
when i echo $file;, it gives url http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf but the function not working to delete the pdf file.
I would appreciate for any help where i can delete my pdf files from server. thank you.
we can't delete file using URL. we need absolute path. try this-:
$file = FCPATH.'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
try to remove space in pdf #4.pdf in your url
http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf
You need the absolute path to the file, I mean something like this
/Users/me/..../my_sites/pdf
The path depends of where is your controller. I don't know how codeigniter works.
EDIT
$file = dirname(__FILE__). DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
It will give you this :
C:\xampp\htdocs\my_site\application\controllers\..\..\pdf files\developer_team#gmail.com\pdf #4.pdf
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!
The script below takes a named file that resides in the "myplugin" folder (the folder that the script itself resides in) and runs file_get_contents() on it to load the contents into memory, then does some preprocessing on the contents before finally inserting it as a post into the WordPress database via the wp_insert_post method.
$my_post3 = array();
$my_post3['post_title'] = 'Privacy Policy';
if(file_exists(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt'))
{
$my_privacy_policy = file_get_contents(ABSPATH.'/wp-content/plugins/myplugin/pages/privacy_policy.txt');
}
else
{
$my_privacy_policy = "";
}
$my_post3['post_content'] = addslashes($my_post3_replace);
$my_post3['post_type'] = 'page';
$my_post3['post_status'] = 'publish';
wp_insert_post($my_post3);
This method works pretty good. However, this method forces me to write a different routine for every file I want to use as the basis of a new page.
What I would like to do instead, is create a folder called "pages" and place my .txt files in that, then run a for loop on the contents of the folder, creating a new page for each file in the folder. I'd like to use the file name (minus the .txt extension) as the name of the page.
For example, the pages folder may have these files:
About Us.txt
Contact Us.txt
And the routine would result in the creation of two new pages in WordPress site, one called "About Us" containing the content found in that file. The other page would of course be "Contact Us" with the contents of that file.
In this way, I can just drop an unlimited number of named and prepopulated .txt files into that folder and when I activate my plugin, it creates those pages.
I just need some help with the for loop and how to reference the folder and files.
I will also have a folder called "posts", which will do the same for posts that this routine does for pages.
Thanks in advance for your help and suggestions.
Update based on #clientbucket answer:
DEFINE ('PAGES', './pages/');
$directory_pages = new DirectoryIterator(PAGES);
foreach ($directory_pages as $files) {
if ($files_pages->isFile()) {
$file_name_page = $files_pages->getFilename();
$my_page_content = file_get_contents(PAGES. $file_name_page);
$my_page['post_content'] = addslashes($my_page_content);
$my_page['post_title'] = $file_name_page;
$my_page['post_type'] = 'page';
$my_page['post_status'] = 'publish';
wp_insert_post($my_page);
}
}
DEFINE ('POSTS', './posts/');
$directory_posts = new DirectoryIterator(POSTS);
foreach ($directory_posts as $files_posts) {
if ($files_posts->isFile()) {
$file_name_post = $files_posts->getFilename();
$my_post_content = file_get_contents(POSTS. $file_name_post);
$my_post['post_content'] = addslashes($my_post_content);
$my_post['post_title'] = $file_name_post;
$my_post['post_type'] = 'post';
$my_post['post_status'] = 'publish';
$post_id = wp_insert_post($my_post);
stick_post($post_id);
}
}
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(./pages/) [directoryiterator.--construct]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\mytestsite\wp-content\plugins\myplugindirectory\myplugin.php:339
Line 339 is here > $directory_pages = new DirectoryIterator(PAGES);
Here is another way you could try.
DEFINE ('PAGES', './pages/'); //Define the directory path
$directory = new DirectoryIterator(PAGES); //Get all the contents in the directory
foreach ($directory as $files) { //Check that the contents of the directory are each files and then do what you want with them after you have the name of the file.
if ($files->isFile()) {
$file_name = $files->getFilename();
$my_page = file_get_contents(PAGES. $file_name); //Collect the content of the file.
} else {
//Insert nothing into the $my_privacy_policy variable.
}
echo $my_page; // Do what you want with the contents of the file.
}
From the PHP manual here:
http://php.net/manual/en/function.glob.php
They provide this solution for finding all text files in a directory:
<?php
foreach (glob("*.txt") as $filename) {
echo $filename . "\n";
}
?>
Given this example, your actual request is to be able to create a file based on the name in another directory. I'll leave the hard work to you - but this is a simple implementation:
<?php
$source_dir = "/your/directory/with/textfiles";
$target_dir = "/directory/to/create/files/in";
foreach (glob($source_dir . DIRECTORY_SEPARATOR . "*.txt") as $filename) {
$filepart = explode('.',$filename);
file_put_contents($target_dir . DIRECTORY_SEPARATOR . $filepart[0] . ".php");
}
?>