Joomla component + forcedownload - php

i have coded a component (Gallery). And i want to intergrate forcedownload for all items.
But will not work :(, just getting corrupted files. I have tried to use exact same code and run it outside of joomla and its works fine. I have created a template thats totaly empty just
have but its not help.
My (com_component/views/forcedownload/tmpl/default.php)
<?php
if(!isset($_GET["id"]) || empty($this->item)) {
echo "Invalid request";
die();
}
$path = "images/randomtest/catid".$this->item->cat_id."/";
$filename = $path.$this->item->filename;
$file = $this->item->filename;
if(!file_exists($filename)) {
echo "Error: File not found";
die();
}
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: Content-type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile($filename);
?>

The first thing is: Are you using $_GET['format'] = raw? If not in your controller do
if(!isset($_GET["format"]) || $_GET["format"]!='raw') {
$this->setRedirect( JURI::current(). '?format=raw' );
return false;
}
also in your header you are declared content type as: application/octet-stream, are you sure you want this?
also here:
$path = "images/randomtest/catid".$this->item->cat_id."/";
you need, whole SYSTEM PATH not only local one, try using:
$path = JPATH_SITE."/images/randomtest/catid".$this->item->cat_id."/";

Related

php - file_get_contents() for dynamic script

I have a script that outputs an image.
Works fine
include('../myfolder/myImageScript.php'); // outputs image on page
Fails
echo file_get_contents('../myfolder/myImageScript.php'); // nothing displayed
I think this fails because in php a script, in my case myImageScript.php, isn't executed when called via the file_get_contents() function, but is when called using a include() the script is executed.
I am struggling to get a zip function to work due to the empty output of file_get_contents().
the file i'm trying to call via file_get_contents() is:
myImageScript.php
$imgstr = "data:image/jpeg;base64,/9j/........... rest of string";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers
header('Content-Type: '.$matches[1]);
//header("Content-Type: image/jpeg"); // tried this made no difference
// Output the actual image data
echo $content;
Any help would be greatly appreciated.
Something like this should work, BUT you need to enable ZipArchive http://php.net/manual/en/class.ziparchive.php (should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WCh4h2fgqDAWcc019AqwTHwDtu1UmMRQnkdpuHRU6gZ3uWOOaHILmuScc6LlFDhKuwwgiqsjQNgAD/UWgFZaKuq/w0AHIAuHIYReR5+A4C12HkEksSfRvuqiuxR4GebSFw7SraMqoRuXvK2t+Z+JDb22bsxDqBh+YRVCO5RgT81JnEGiNtNvvKKwl/IzJKql8ORadqQuSZis7CANCWYnIScOyAiJHayFIUIpM8r0GUstsrbA4HhC2nJi9LwDuihKkuhEQpgAAiEQpjyc99aWHMppz2gSLBlCL9iFQrW2pdz0TDPCkGCRgQjU9GVPpZQAkgIICWHfQhABkNkM1svQxg9wcJfWSn1AlxI5DA3COYjbbaLJBKzhQRuiF4Cn8nMiMXgQ+uOAkBFDDA2wxABkPJiMe8+OUaECVNLMZUJI755xtoHmwXnoNuugUQp4bGLzf0dvrriy2wsAMD4A377YJjSgDfD0QAADs=";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
$content = base64_decode($matches[2]);
$zip = new ZipArchive;
$filename = tempnam("/tmp", "testmeZip");
$res = $zip->open($filename, ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.gif', $content);//you can use $matches to figure out extension
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
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=\"test.zip\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize($filename));
// output the file
readfile($filename);

php download not working for &

I have this php function to download files from my public_html.
function download($file){
$dir = "RepList/";
$path = $dir.$file;
if(!file_exists($path))
{
die("Error : The file does not exists !");
}else{
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Typr: application/w3g");
header("Content-Transfer-Encoding: binary");
readfile($path);
}
}
if (isset($_GET['download']))
{
if(!empty($_GET['download']))
{
$file = $_GET['download'];
download($file);
}
}
For download I use something like:
<a class="download" id="download'.$i.'_" href="../download.php?download='.$cc->EList[$i]->getEName().'" target="_blank">Download</a>
If I have "&" symbol in my file name, I will receive "Error : The file does not exists !".
I worked on this like 1 year ago and now I want to fix the error.
Any advice? Something easy & fast.
You should probably use urlencode() function and change creating HTML link to:
<a class="download" id="download'.$i.'_" href="../download.php?download='.urlencode($cc->EList[$i]->getEName()).'" target="_blank">Download</a>
otherwise & character is treated as variables separator in url

Download File in Yii

I am trying to write a script in Yii for downloading files from the server.
The files are located in webroot of the Yii project,
but I got every time file not exist error, could anyone see where is wrong:
public function actionDownload($id) {
$audio = Audio::model()->findByPk($id);
$file = Yii::getPathOfAlias('webroot') . $audio->path;
if (file_exists($file)) {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $audio->path);
header('Content-Length: ' . filesize($audio->path));
$audio->downloaded = $audio->downloaded + 1;
$audio->save();
}else{
echo "file not exist: ".$file;
}
exit;
}
error I got is:
file not exist: /var/www/vhosts/ikhwanbiz.org/httpdocs/userfiles/reklames/media/deneme/sen%20dep%20olmisem.mp3
Thanks
Regards
Bili
Bili, this works well for me and seem to be fine on most browsers.
$filename = 'your_file_name.csv';
header('Content-Disposition: attachment; charset=UTF-8; filename="'.$filename.'"');
$utf8_content = mb_convert_encoding($content, "SJIS", "UTF-8");
echo $utf8_content;
Yii::app()->end();
return;
Hope it helps, good luck!
It looks like the filename portion $audio->path is URL-encoded, while the name of the actual file on the server is not. You should fix it at the source (no idea where that path is set from), but in the meantime an easy workaround would be to write
$file = Yii::getPathOfAlias('webroot') . urldecode($audio->path);
This is more of a php question than a yii one.
for eg,
<?php
header("Content-disposition: attachment; filename=huge_document.pdf");
header("Content-type: application/pdf");
readfile("huge_document.pdf");
?>
source: http://webdesign.about.com/od/php/ht/force_download.htm

PHP downloads at 0 bytes

I have ZIP files in a directory that is one step up from the root directory (to prevent hotlinking etc...). Here is the code:
<?php
$filename = $_GET['id'];
if(!$filename){
header("Location: index.html");
} else {
function send_download($filename){
$file_path = '../../../../downloads/' . $filename . '.zip';
$file_size=#filesize($file_path);
header("Content-Type: application/x-zip-compressed");
header("Content-disposition: attachment; filename=$filename");
header("Content-Length: $file_size");
readfile($file_path);
exit;
}
send_download($filename);
}
?>
All the ZIP files are fine but using this method on an 'a' tag causes the downloads to be 0 bytes in file size! :(
Any ideas as to why?
Many thanks!
Can you try changing the Content-type to the following:
Content-type: application/x-zip;
And before you do, check if the file exists.
<?php
$filename = $_GET['id'];
if(!$filename){
header("Location: index.html");
} else{
function send_download($filename){
$file_path = '../../../../downloads/' . $filename . '.zip';
if (file_exists($file_path))
{
$file_size=#filesize($file_path);
header("Content-Type: application/x-zip-compressed");
header("Content-disposition: attachment; filename=$filename");
header("Content-Length: $file_size");
readfile($file_path);
exit;
}
send_download($filename);
}
else
die("Error 404!");
}
?>
header("Location: http://www.fqdn.tld/file.ext");
Based on _GET["id"] being > 0 and not null, you've created a function which has been used directly after, so you've just added more lines of code for no required purpose.
I see you have added an "#" sign as people have previously commented, however, the only way for you to begin fixing this is by:
Removing the # sign as you should never use it, very bad practice, you should cater for all exceptions in your code, it makes for a really good programmer. (Scripting in PHP)
error_reporting(E_ALL);
Place point b) on it's own line but after the <?php - so we can see a full list of errors.
Your code is fine, the problem you have is permissions, ensure that apache has access to your "files" repository, the fact you are able to check that the file is there suggest slight permissions and the files exists, the point that 0 bytes are being returned suggest reading privileges are denied at Apache level.
Right, after a bit of Googling and some blood, sweat and tears I have finally found a solution!
<?php
$filename = $_GET['id'];
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename=" . $filename);
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
readfile('../../downloads/' . $filename . ".zip");
exit;
?>
Many thanks to all of whom shed some light on this!
And here is the code with the filesize:
<?php
$filename = $_GET['id'];
$file = "../../downloads/" . $filename . ".zip";
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename=" . $file);
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-length: " . filesize($file));
readfile($file);
//echo filesize($file);
exit;
?>
Only one mistake we all are doing check below.
readfile($file); //$file should be relative not absolute. That's it.
Thanks,
Anirudh Sood.

Protecting Downloads

I was just testing this download script below. The downloading works fine but the downloaded zip or rar archive is always corrupt and cannot be opened. I tested it on local development server as well as my hosting account.
I am just trying to learn how this works but I don't really understand it.
All help is appreciated!
Test Code:
<?php
$is_logged_in = 1;
$path_to_file = 'downloads/tes.zip';
$file_name = 'test.zip';
if ($is_logged_in == 1)
{
header("X-Sendfile: $path_to_file");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$file_name\"");
exit;
}
?>
<h1>Permission denied</h1>
<p>Please Login first!</p>
It mostly probable that you have something appended/prepended to the file. Try to use buffering and cleaning.
<?php
ob_start();
$is_logged_in = 1;
$path_to_file = 'downloads/tes.zip';
$file_name = 'test.zip';
if ($is_logged_in == 1)
{
$fp = fopen($path_to_file, 'rb');
if(is_resource($fp))
{
ob_clean();
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($path_to_file));
header("Cache-Control: max_age=0");
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Pragma: public");
fpassthru($fp);
die;
}
} else {
echo "<h1>Permission denied</h1>";
echo "<p>Please Login first!</p>";
}
Have you configured your webserver (Apache in particular) to load mod_xsendfile? Without that module installed, your script essentially does nothing.

Categories