Php Image save as dialog box - php

I wanted to open a save image dialog box when I click on an image. I managed to open the same but when saved, it does not save open saved image as the content of image is not saved somehow.
PHP code:
$imageName = $_GET['i'];
$imageName = $imageName . '-HR.jpg';
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$imageName");
header("Content-Length: " . filesize("$imageName"));
$fp = fopen("$imageName", "r");
fpassthru($fp);
The passing URL is something like:
mydomain/download_image.php?c=atherothrombosis&i=embolus-carotid-artery-illustration
Please suggest solution. Thanks.

add this header also
header("Content-Type: application/force-download");

I managed to do so by using below code:
<?php
$imageName = $_GET['i'];$imageName = $imageName . '-HR.jpg';
$imageCatName = $_GET['c'];
$imageCatName = ucwords($imageCatName);
$file_path = $docRoot . '/static/media/images/content/image_library/'.$imageCatName . '/'. $imageName;
if(file_exists($file_path)) {
header("Content-disposition: attachment; filename={$imageName}");
header('Content-type: application/octet-stream');
readfile($file_path);
}else {
echo "Sorry, the file does not exist!";
}
?>
still thanks a lot for your support. :)

Related

How can I add a download button?

I have this code which outputs a QR code:
<?php
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('Soci', 'Nom', 'Cognoms', 'eCorreu')))
->from($db->quoteName('#__rsform_socis'))
->where($db->quoteName('username') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$codeContents = $db->loadObjectList();
$data .= "Soci Nº: {$codeContents[0]->Soci}\n ";
$data .= "Nom: {$codeContents[0]->Nom} ";
$data .= "{$codeContents[0]->Cognoms}\n";
$data .= "e-correu: {$codeContents[0]->eCorreu}";
$tempDir = JPATH_SITE . '/images/';
$fileName = 'qr_'.md5($data).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($data, $pngAbsoluteFilePath);
}
echo '<img src="'.$urlRelativeFilePath.'" />';
?>
How can I add a download button so the user can download the code to the computer?
Thanks,
Dani
This is more of a HTML question, so lets get started: There is an attribute called "download" and you can use it like this:
echo 'Download QR';
It downloads the file as the name you supply here. So if the image url on your server is: wadAHEybwdYRfaedBFD22324Dsefmsf.png it would download the file as "qrcode.png". Unfortunately this is not supported in all browsers. Another easy fix is to make a form that has your filename as an action like so:
echo '<form method="get" action="'.$urlRelativeFilePath.'"><button type="submit">Download QR Code!</button></form>';
Another way (little more code) to do this is using PHP with some specific headers like this:
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// Download here
?>
It works for large and small files and also for many different filetypes. Info found here: http://www.finalwebsites.com/forums/topic/php-file-download
Well, you are obviously creating a .png picture file of the QR code with your script. So simply add a link to the location of the picture:
echo "Download";
This will however just redirect the user to the picture in his browser.
If you want to force a download you will need to use PHP headers to send the file to the visitors browser.
For example make a script and call it download_code.php.
Then add:
echo "Download";
And in the download_code.php:
$handle = fopen("/var/www/yourdomain.com/images/" . $filename, "r");
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Length: ' . filesize("/var/www/yourdomain.com/images" . $filename));
flush();
readfile("/var/www/yourdomain.com/images" . $filename);
fclose($handle);

Why I'm unable to download a pdf file which is already present onto server?

Following is the code:
define(ADMIN_ROOT,'/var/www/abc/pqr/web/control/');
$filename = $test_data['test_name'];
$flname = ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename;
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"" .$flname. ".pdf\"");
The pdf file is already present over there at the directory
/var/www/abc/pqr/web/control/modules/tests/test_pdfs/
Also it has all the permissions assigned.But when I try to download a file, it's downloading some different file with same name but the file is not in a format which could be opened. In short the desired file is not getting downloaded. Can anyone please help me in correcting my issue?
You must flush the file contents to the browser, headers won't do that.
So: readfile( $flname ) http://php.net/manual/pt_BR/function.readfile.php
Please try this
<?php
$filename = $test_data['test_name'];
$file = dirname(__FILE__) . "/modules/tests/test_pdfs/" . $filename;
//$file = "/var/www/htdocs/audio/" . $filename;
if (file_exists($file)) {
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=" . str_replace(" ", "_", basename($file)) . ";");
header ("Content-Length: " . filesize($file));
readfile($file);
die();
}
else {
//ERROR MESSAGE HERE..........
}
?>
Please change this line
header("Content-Type: application/pdf");
to
header ("Content-type: octet/stream");
You can also use the following code for download any type of file extensions:
<?php
$filename = $test_data['test_name'];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile(ADMIN_ROOT.'modules/tests/test_pdfs/'.$filename);
exit();
?>

download image from another server url without saving in my server folder

I have problem in download image from url,
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
in this code file is saving in my server folder .but i needed without saving in my server it needs to be download to user.
set the correct header and echo it out instead of file_put_contents
$url = 'http://example.com/image.php';
header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);
Use application/octet-stream instead of image/jpg:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
— RFC 2616 – 19.5.1 Content-Disposition
EDIT
function forceDownloadQR($url, $width = 150, $height = 150) {
$url = urlencode($url);
$image = 'http://chart.apis.google.com/chart?chs='.$width.'x'.$height.'&cht=qr&chl='.$url;
$file = file_get_contents($image);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=qrcode.png");
header("Cache-Control: public");
header("Content-length: " . strlen($file)); // tells file size
header("Pragma: no-cache");
echo $file;
die;
}
forceDownloadQR('http://google.com');
if you want to download the file onto your webserver(and save it), just use copy()
copy($url, 'myfile.png');

php download file: header()

I need some eduction please.
At the end of each month, I want to download some data from my webserver to my local PC.
So, I've written a little script for that, which selects the data from the DB.
Next, I want to download it.
I've tried this:
$file=$month . '.txt';
$handle=fopen($file, "w");
header("Content-Type: application/text");
header("Content-Disposition: attachment, filename=" . $month . '.txt');
while ($row=mysql_fetch_array($res))
{
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
If I run this, then the file is created, but my file doesn't contain the data that I want. Instead I get a dump from the HTML-file in my browser..
What am I doing wrong..
Thanks,
Xpoes
Below script will help you download the file created
//Below is where you create particular month's text file
$file=$month . '.txt';
$handle=fopen($file, "w");
while ($row=mysql_fetch_array($res)){
$writestring = $row['data_I_want'] . "\r\n";
fwrite($handle, $writestring);
}
fclose($handle);
//Now the file is ready with data from database
//Add below to download the text file created
$filename = $file; //name of the file
$filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binary\n");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-Length: ".filesize($filepath));
readfile($filepath);
exit;
Your current code does not output a file, it just sends headers.
in order for your script to work add the following code after your fclose statement.
$data = file_get_contents($file);
echo $data;

How to echo raw post data in PHP?

My goal is to simply echo $_POST['imageVar']; back with content headers as a quick and dirty means to "export" an image from a flash application. I saw an example of this as follows, but it does not work with my php version/config:
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $jpg;
}
So as a work around I created a script that saves the image to the server, reads the image and echos it back, then deletes the image. I don't like this approach as I need to have a directory that is writable by the apache user (im on a shared server). Is there a way to accomplish what I am doing here without hte need to use the temp file?
<?
$fileName = basename( $_FILES['uploadedfile']['name']);
$tempFile = "uploads/" . $fileName;
$fileSize = $HTTP_POST_FILES['uploadedfile']['size'];
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $tempFile)) {
        $fh = fopen($tempFile, 'r');
        $fileContents = fread($fh, $fileSize);
        header('Content-Type: image/jpeg');
        header("Content-Disposition: attachment; filename=$fileName");
        echo $fileContents;
        fclose($fh);
        unlink($tempFile);
} else {
        echo "upload fail";
}
?>
Any input or ideas greatly appreciated! Thanks for looking
You can just use:
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=$fileName")
readfile($_FILES['uploadedfile']['tmp_name']);
No need to move it if you're not going to keep it.
On a side note, regarding the first solution you were looking at, does an echo file_get_contents('php://input'); not work?
$s = file_get_contents('php://input');
// add headers for download dialog-box
header('Content-Type: image/jpeg');
header("Content-Disposition: attachment; filename=".$_GET['name']);
echo $s;
What about that?

Categories