Error while downloading Image on server using PHP - php

I have written following code in my Yii framework controller. This code is working fine on my localhost but not working on server.
Can somebody please tell me whats wrong with the code
Following is my code which I have written in controller
public function downloadFile($dir,$file,$extensions=[]){
if(is_dir($dir)){
$path = $dir.$file;
if(is_file($path)){
$fileinfo=pathinfo($path);
$extension=$fileinfo["extension"];
if(is_array($extensions)){
foreach($extensions as $e){
if($e===$extension){
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($path);
return true;
}
}
}
}else{
echo"error";
}
}
}
public function actionDownload(){
if(Yii::$app->request->get('file')){
$this->downloadFile("media/offer/",Html::encode($_GET["file"]),["jpg","png"]);
}
}

You tagged yii2, but it's not yii2, its pure php.
How about use framework to do this?
public function actionFile($filename)
{
$storagePath = Yii::getAlias('#app/files');
// check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new \yii\web\NotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
Yii2 - sendFile()
^Change storagePath to your file directory.
And that's all, nothing more to do.

Replace this function with yours,
public function downloadFile($dir,$file,$extensions=[]){
if(is_dir($dir)){
$path = $dir.$file;
if(is_file($path)){
$fileinfo=pathinfo($path);
$extension=$fileinfo["extension"];
if(is_array($extensions) && in_array($extension, $extensions)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path);
exit;
}
}else{
echo"error";
}
}
}
I just called this with following,
downloadFile("/var/www/html/", "test.php", ['php']);
and it worked for me.

Related

How to download image file by force download

I am trying to download image file in CI but getting error when I open download image file. Need help :(
$file_name = $_GET['file_name'];
$file_path = "./ups_printimages/".$file_name;
if(file_exists($file_path))
{
$this->load->helper('download');
$data = file_get_contents($file_path); // Read the file's contents
$name = 'ups_label.png';
force_download($name, $data);
}
else
{
echo "file does not exist";
}
GOD. Found out the solution :)
if(!file)
{
File doesn't exist, output error
die('file not found');
}
else
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
ob_clean();
flush();
readfile($file);
exit;
}
Use header to force download. Use the code below
$file_name = $_GET['file_name'];
$file_path = "./ups_printimages/".$file_name;
if(file_exists($file_path))
{
header('Content-Type: image/jpeg');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_name) . "\"");
readfile($file_path);
}
else
{
echo "file does not exist";
}
Hope this helps yoiu

Header Content-length not working

I'm doing file download with renaming it before. Everything works except size. I can't set file size with
header('Content-Length: ');
even I'm setting it to
header('Content-Length: 15444544545');
it's not working. I'm using PHP codeigniter framework, where is the problem?
EDIT: more code:
$file_data = array(
'originalName' => $post_info['file_info'][0]['original_name'],
'fakeName' => $post_info['file_info'][0]['file_name'],
'modificationId' => $post_info['file_info'][0]['modification_article_id'],
'extension' => end(explode('.', $post_info['file_info'][0]['original_name'])),
'name' => str_replace(".".end(explode('.', $post_info['file_info'][0]['original_name'])), "", $post_info['file_info'][0]['original_name']),
'filesize' => filesize($post_info['file_info'][0]['file_name'])
);
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $file_data['name'] . '.' . $file_data['extension']);
header('Content-Length: ' . filesize(base_url().$file_data['fakeName']));
// Read file
readfile(base_url().$file_data['fakeName']);
//print_r($file_data);
echo "<script>window.close();</script>";
EDIT: Solution
there was a server problem
You can try like this:
$mm_type="application/octet-stream";
header("Cache-Control: public, must-revalidate");
header("Pragma: hack");
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($fullpath)) );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary\n");
readfile($fullpath);
wrong usage of base_url().
where is your file stored?
maybe you can try the constant FCPATH instead of call function base_url()
and you have the filesize stored in $file_data['filesize']
finally there should not be a line echo "<script>window.close();</script>"; in your php script when the file content was output.
You tried with download_helper?? Sintax: force_download($filename, $data).
Also in your code you're reading file through URL. Use file system path instead.
From controller action:
<?php
public function download()
{
//Your code here...
$filePath = realpath(FCPATH.DIRECTORY_SEPARATOR.'uploads/myfile.pdf'); //FakeName????
force_download($file_data['fakeName'], readfile($filePath));
}
If my solution don't works give me a touch to give you other way.
Note: FCPATH is the front controller path, a public folder of server e.g.(/var/www/CodeIgniter). Other path constants are already defined on index.php (front-controller).
A print of $file_data['fakeName'] will be useful.
If your CodeIgniter version don't have download_helper make your own... refer to CI docs for full explanation. There is the force_download function code:
function force_download($filename = '', $data = '')
{
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);
}

force download on restler function call

I got the following function in restler
/**
* get updateFiles by name
*
* one could get the last update file
*
* #status 201
* #return file
*/
function getupdateFile($filename) {
$file = 'Plakat.jpg';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
else {
return "<h1>Content error</h1><p>The file does not exist!(".dirname(__FILE__).'/'.($file).")</p>";
}
}
The problem is that the file is there permissions are correct but no file download is
forced.
Where is the failure?
It always return "The file does not exist but it does.
I searched for different problems with force download an php but this seems to be a problem with restler?
Thx
Ingo
You can try this code below which happens to work fine
$file = 'Plakat.jpg';
if(file_exists($file))
{
header("Content-Type: image/png");
header('Content-Disposition: attachment; filename="ImageName.png"');
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
readfile($file);
}
exit();

Downloading file from localhost site in PHP

When i am download a file with extention like mp3,flv etc it will now download it start buffering And when I remove extention from the file it downloads ...
can you please tell whats the problem behind that ...
file to download is => theangelfoundation-12-5-2012-09-17-27-somebody.mp3
Thanks in advance ..
$file_types=array();
$file_types['mp3'] ='audio/mpeg';
$file_types['mpeg'] ='video/mpeg';
$file_types['mpg'] ='video/mpeg';
$file_types['pdf'] ='application/pdf';
$file_types['pps'] ='application/vnd.ms-powerpoint';
$file_types['ppt'] ='application/vnd.ms-powerpoint';
$file_types['ps'] ='application/postscript';
$file = 'you.mp3';
download($file,$file_types);
function download($file_name,$file_types){
$file = $file_name;
$ext = end(explode('.',$file_name));
if($ext && array_key_exists($ext,$file_types)){
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
else {
die("this is not a downloadable file");
}
}
?>
download ok.txt

Download image with Zend - PHP header: wrong file format

First of all, I know this question has already been asked but I can't solve it anyway.
I need to set a link to download images(jpg).
I read various posts found here and with google but it's always the same results:
I can download the file but it's still the same error. The jpeg format is not correct.
Erreur d'interprétation du fichier
d'image JPEG (Not a JPEG file: starts
with 0x0a 0x20)
When I test this in a file without a controller, it's ok but the script in a controller doesn't work.
Here is the code for tests:
$file = '{document_root}/www/themes/default/images/common/background1.jpg';
if (file_exists($file))
{
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-length: ' . filesize($file));
readfile($file);
exit;
}
This code works in a simple php file. I download the picture and can open it.
But within my controller, the file is not good.
I found that the tag ?> can add spaces but my controllers doesn't have this closing tag.
I've tested some code with the Zend objects found in various posts but it's the same error.
I've tried various way to read the file (file_get_content(), fread() ...) with the same result.
I assume there's something wrong with my Zend controller.
I'm now testing my file according to this post:
php file download: strange http header
Any clue will be really appreciated.
Thanks for your help and sorry for my bad english.
[EDIT: 21/06/2011 - 6h38]
Here is the code of the action
public function downloadAction()
{
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$img = $this->_getParam('img');
// Process the file
$config = Zend_Registry::get('config');
$width = $config->catalog->image->original->maxWidth;
$height = $config->catalog->image->original->maxHeight;
$prefix = $width . 'x' . $height . '_';
$filename = $prefix . $img;
$file = Zend_Registry::get('document_root') . '/data/images/catalog/products/' . $this->_getParam('pid') .'/'. $filename;
if (file_exists($file))
{
$this->getResponse()
->setHeader('Content-Disposition', 'attachment; filename='.$filename)
->setHeader('Content-Transfer-Encoding', 'binary')
->setHeader('Content-Length', filesize($file))
->setHeader('Content-type', 'image/jpeg');
$this->getResponse()->sendHeaders();
readfile($file);
exit;
}
}
This action is not called directly. I test if a parameter exists in the url.
If true then from the listAction, I call the downloadAction().
I've tried to disable the view and layout in both action but there's some html rendered.
I had the same problem sending content after decrypt file's content.
0x0a means new line. You probably have some new line after the ?> tag in some included class.
Put
ob_clean();
flush();
before
readfile($file);
something like this:
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
This work out fine for me. Hope it helps.
Regards
I codeing working zend framework :)
public function dowloadfileAction(){
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
if ($this->_user->isUserLogin()) {
$path_file = 'public/uploads/file/';
$filename = $this->_getParam('file');; // of course find the exact filename....
$file = $path_file.$filename;
//zfdebug(mime_content_type($file)); die();
if (file_exists($file)) {
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: '.mime_content_type($file));
header('Content-Disposition: attachment; filename="'. basename($file) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
readfile($file);
}else{
echo "File does not exist";
}
}else{
echo "Please Login";
}
exit;
}

Categories