Most of the web applications stored confidential documents on different server/location and use these documents by a secured web API. But in case, if you are using the same server to stored the confidential documents, then you must need to secure the documents by session so that only authorized users can access these documents (like PDF, Images, ZIP, etc). Using this way you can also restrict unauthorized users to access any folder on your server.
You can achieve this in codeigniter or any other framework by using the following steps:
1) Create a htaccess file on root, if already created then skip this step.
2) Put this code in the .htaccess file:
Code:
RewriteEngine On
RewriteRule ^/?document_folder_path(.*) http://yourdomain.com/controller_file/index_function/?req=%{REQUEST_URI} [R=301,L]
a) Replace "document_folder_path" with your document folder path
b) Replace "yourdomain.com" with your domain name
c) controller_file: create a controller in controller folder with an index function
3) Put the below code to your controller file:
Code:
class controller_file extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
//print_r($_GET);
if( !empty( $_GET['req'] ) )
{
// check if user is logged
if(!empty($this->session->userdata("is_loggedin")))
{
$url = $_GET['req'];
$ptype=1; // tracking the type of file is being requested
if (strpos($url, 'report_problem') !== false) {
$pdf_name = md5(time()).'.png';
$ptype=2;
}elseif(strpos($url, 'Signature') !== false) {
$filename = "signature.zip";
$ptype=3;
}else{
$pdf_name = md5(time()).'.pdf';
}
$pdf_file = $_SERVER['DOCUMENT_ROOT'].$url;
if( file_exists( $pdf_file ) )
{
if($ptype == 2){
header('Content-Type: image/png');
echo file_get_contents($pdf_file);
}elseif($ptype == 3){
//echo $filename.'<br> '.$pdf_file; die;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($pdf_file));
ob_end_flush();
@readfile($pdf_file);
}else{
header('Content-Type: application/pdf');
echo file_get_contents($pdf_file);
}
//echo file_get_contents($pdf_file);
}else{
redirect('My404');
}
}else{
redirect('My404');
}
}
}
}