Reputation: 1273
I ma using CodeIgniter3 to build projects. However I am not sure where is the best place to store generated PDF files. I do not want to keep them in MySQL due to its size.
I do not want people to access direct links like: http://mydomain/pdf/file.pdf but I would like to give this kind of access for codeigniter logged users.
What is the best way to do that?
Upvotes: 1
Views: 1200
Reputation: 16997
Create site/pdf_files/.htaccess
file and add this line:
Deny from all
Make router config as follows
/*
anything in second segment of pdf controller will be routed to
index method
serve file like :
http://example.com/pdf/myfile.pdf
*/
$route['pdf/(:any)'] = "pdf/index/$1";
/*
Note: if you got some more methods in same controller prefer below one
because, with above one, anything in second segment will be routed to
index method
$route['pdf/display/(:any)'] = "pdf/index/$1";
and serve files like
http://example.com/pdf/display/myfile.pdf
*/
and then while serving pdf to user prefer codeigniter file helper like below
class Pdf extends CI_Controller
{
function download_file($path, $name)
{
// make sure it's a file before doing anything!
if(is_file($path))
{
// get the file mime type using the file extension
$this->load->helper('file');
header('Content-Type: '.get_mime_by_extension($path));
header('Content-Disposition: attachment; filename="'.basename($name).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path)); // provide file size
header('Connection: close');
readfile($path);
die();
}
}
public function index($file)
{
// here you check whether user logged in or not
$this->download_file('pdf_files/'.$file, $file);
}
}
Upvotes: 2
Reputation: 2218
Store the PDF outside of your document root in a location that's not public.
You can use application logic to allow logged in users to view/access:
class pdf extends ci_controller{
public function view()
{
//check if user is logged in and has permission to view
//set proper header information
//readfile('non_public_path\to\pdf);
}
}
As long as your pdf is outside of your public directories - sending a request to domain.com/pdf/view will only render the pdf if the user is logged in and has permissions to view.
Upvotes: 0