How to echo raw post data in PHP? - 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?

Related

php download link to rar

I'm creating a website on my localhost that should let people download some .rar files.
In my index I've created some tags like this:
$filename = "Test001.rar";
'.$filename.'';
This is just an example of one single file, but in my php file 'download.php' I've got the problem when I want to download the .rar file
This is download.php
<?php
echo "Welcome to Knowledge!";
if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file'])
{
$file = $_GET["file"];
$path = 'C:\xampp\htdocs\TestSite'."\\".$file;
}
$err = $path.'Sorry, the file you are requesting doesnt exist.';
if (file_exists($path) && is_readable($path))
{
//get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/x-rar-compressed, application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($filename);
}
?>
It opens the stream in the right way, but I get that the file size is about 200 bytes and not the full length that is about 200MB.
How can I fix this problem?
Remove the echo statement, there should not be any output before the headers. Change readfile($filename) to readfile($file)

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;

PHP readfile() returning corrupted data

In my function I am saving an image decoded from a base64 string:
function saveImage(){
//magic...
define('UPLOAD_DIR', '../webroot/img/');
$base64string = str_replace('data:image/png;base64,', '', $base64string);
$base64string = str_replace(' ', '+', $base64string);
$data = base64_decode($base64string);
$id = uniqid();
$file = UPLOAD_DIR.$id.'.png';
$success = file_put_contents($file, $data);
}
The above function works properly and the images are saved and not corrupted in the specified folder.
In the next function I am now trying to force download the image to a user:
function getChart($uniqid= null){
if($uniqid){
$this->layout = null;
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
} else exit;
}
Image downloaded from the server is corrupted and cant be displayed. After opening the downloaded file in a text editor I noticed that a new line character is added at the very top. After deleting the character and saving the file it opens properly and is being displayed properly.
How can I fix this?
What you describe can have multiple issues that are hidden until you actually open the downloaded file.
Instead make your code more robust and check pre-conditions, here if headers have been send already and to clean any possible existing output buffer and give error if that is not possible:
function getChart ($uniqid = null) {
if (!$uniqid) exit;
$this->layout = null;
if (headers_sent()) throw new Exception('Headers sent.');
while (ob_get_level() && ob_end_clean());
if (ob_get_level()) throw new Exception('Buffering is still active.');
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
}
header("Content-length: $file_size")
This header tells the browser how large the file is. Some browser need it to be able to download the file properly. Anyway it's a good manner telling how big the file is. That way anyone who download the file can predict how long the download will take.
header("Content-type: $file_type")
This header tells the browser what kind of file it tries to download.
header("Content-Disposition: attachment; filename=$file_name");
This tells the browser to save this downloaded file under the specified name. If you don't send this header the browser will try to save the file using the script's name.
BUT you need to flush buffer, with flush(); or in your case with ob_flush(); right above first exit;
check if you are outputing something before calling readfile:
// add ob_start() at the very top of your script
function getChart($uniqid= null){
echo strlen(ob_get_clean()); die(); // if it's not 0 then you are definetly echoing something
if($uniqid){
$this->layout = null;
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
} else exit;
}
EDIT (to force download):
function getChart($uniqid= null){
if($uniqid){
$image = $uniqid;
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $image);
header("Content-Type: image/jpg");
header("Content-Transfer-Encoding: binary");
readfile($image);
} else exit;
}
getChart("060620121945.jpg");
Try this (just to render image):
function getChart($uniqid= null){
if($uniqid){
$mime_type = "image/png";
$content = file_get_contents('../webroot/img/'.$uniqid.'.png');
$base64 = base64_encode($content);
return ('data:' . $mime_type . ';base64,' . $base64);
} else exit;
}
I have had this problem several times. Here's the solution that I used:
Almost always it turned out that I had forgotten to turn off unicode BOM encoding in my download.php file which adds something to the front of the downloaded file and therefore corrupts it.
So the solution is to turn off unicode BOM in download.php.
Just use ob_clean(); before readfile()

Php Image save as dialog box

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. :)

Categories