I have uploaded few images on my server which will be downloaded to my android application by passing a url. I have written a php file which displays the image. I pass the URL to my android application like this :
'http://myURL/getImage.php?image=logo.png'.
When I copy paste the URL directly in browser the image is displayed correctly.
However the image file is not getting downloaded on my android application. I know that android code is correct because when I am giving any other random image URL the image is downloading correctly. Do I have to give something else in my php file to make the image 'downloadable'.
Image.php
<?php
echo '<img src="Images/'.$_REQUEST['image'].'"/><br />';
?>
It seems you want the PHP to output the image directly. Instead, your code is generating an HTML with the image on it. Although your browser displays similar results, the underlying content is different.
What you actually need could be this:
<?php
$filepath = 'Images/'.$_REQUEST['image'];
$filename = basename($filepath);
$ctype = 'image/jpeg'; // assuming it is a .jpg file
if (is_file($filepath)) {
header('Content-Type: '.$ctype);
header('Content-Length: ' . filesize($filepath));
header('Content-Disposition: attachment; filename="'.$fileName.'"');
echo file_get_contents($file);
exit();
} else {
header("HTTP/1.0 404 Not Found");
// you may add some other message here
exit();
}
This is vulnerable to hazardous $_REQUEST['image'] input. Just filter it somehow. Also you must generate the correct $ctype for the image file.
Related
I am trying to display multiple images from my database through a loop. Basically it's something like this
while loop is running{
$_SESSION['path'] = $imageURL;
echo '<img src="pic.php">';
}
my idea is the pic php gets the path then displays it. Then another path comes in and it returns the image again.
HOWEVER IT DID NOT. It just returns the last image retrieved and repeat it until the loop is done.
so instead of displaying a.png, b.png and c.png. What displayed were 3 c.png.
here is my pic.php
<?php
session_start();
$name = $_SESSION['path'];
$fp = fopen($name, 'rb');
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
?>
I'm particularly new to this stuff so it will be a great help if you guys check this out! TYIA!
Here is what happens:
You access your web page through your favorite browser
The server process your request, and asks PHP to create an HTML file containing 3 <img src="pic.php" />
The server returns the HTML file to your browser
The browser analyze your HTML file and detect it has links to external resources, indeed it has 3 times pic.php, so it begins to ask the server to return the content of this file
The server process again the request and asks PHP to return to him the content of pic.php
The server returns this content, and HTML put it 3 times
You can see at the end, even if you looped 3 times and changed 3 times $_SESSION['path'], the server comes after the war and only see c.php, so it returns it to the browser.
You should adopt another strategy to fetch your images.
Workaround
One way to fix the issue is to fetch image "at demand" like this:
pic.php
<?php
session_start();
$name = filter_var($_GET['q'], FILTER_SANITIZE_URL);
$fp = fopen($name, 'rb');
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
fpassthru($fp);
exit;
?>
index.php (the file you access)
<?php
while loop is running{
echo "<img src='pic.php?q=$imageURL'>";
}
?>
This is one I just can't figure out: I have successfully built an upload feature on a web page to upload files to a MySQL Database. When I go on the server and open them via phpMyAdmin, they all look fine... txt, jpg, pdf, etc.
Yet, after putting together THIS thing (below) to download it, I get a strange problem: All of the text documents (and all other types of files, after I change the extension to 'txt') contain HTML code of the page itself, followed by the original content!
Also, different browsers display differently after the POST. When trying to download a txt file, IE will show the correct data in the ECHO on the page itself (no downloading) with an error message just before it:
Warning: Header may not contain more than a single header, new line detected. in C:\wamp\www\ace\dmain.php on line 82.
Line 82 is 'header("Content-length...'
Neither Firefox nor Chrome show anything. They just allow me to download it.
Here's the code:
<?php
if (isset($_POST['downloadid'])) {
$fileid = $_POST['downloadid'];
try {
$sql = "SELECT * FROM `datastore` WHERE `id` = '".$fileid."'";
$results = $pdo->query($sql);echo $sql;
while ($row = $results->fetch()) {
$filename = $row['filename'];
$mimetype = $row['mimetype'];
$filedata = $row['filedata'];
header("Content-length: strlen($filedata)");
header("Content-type: $mimetype");
header("Content-disposition: download; filename=$filename"); //disposition of download forces a download
echo $filedata;
// die();
} //of While
} //try
catch (PDOException $e) {
$error = '<br>Database ERROR fetching requested file.';
echo $error;
die();
} //catch
} //isset
?>
This:
header("Content-length: strlen($filedata)");
Is not going to produce what you expect. If you look at the headers in wireshark, or another method to view the request you will see that it does not contain an integer.
Use this instead:
header("Content-length: ".strlen($filedata));
After agonizing over fixing it in-place (that is, on the same page with the rest of the html and code), I decided to move it to a dedicated PHP page. After that, it worked fine.
Thanks for the comments!
here is good example and complete source
This is one I just can't figure out: I have successfully built an upload feature on a web page to upload files to a MySQL Database. When I go on the server and open them via phpMyAdmin, they all look fine... txt, jpg, pdf, etc.
Yet, after putting together THIS thing (below) to download it, I get a strange problem: All of the text documents (and all other types of files, after I change the extension to 'txt') contain HTML code of the page itself, followed by the original content!
Also, different browsers display differently after the POST. When trying to download a txt file, IE will show the correct data in the ECHO on the page itself (no downloading) with an error message just before it:
Warning: Header may not contain more than a single header, new line detected. in C:\wamp\www\ace\dmain.php on line 82.
Line 82 is 'header("Content-length...'
Neither Firefox nor Chrome show anything. They just allow me to download it.
Here's the code:
<?php
if (isset($_POST['downloadid'])) {
$fileid = $_POST['downloadid'];
try {
$sql = "SELECT * FROM `datastore` WHERE `id` = '".$fileid."'";
$results = $pdo->query($sql);echo $sql;
while ($row = $results->fetch()) {
$filename = $row['filename'];
$mimetype = $row['mimetype'];
$filedata = $row['filedata'];
header("Content-length: strlen($filedata)");
header("Content-type: $mimetype");
header("Content-disposition: download; filename=$filename"); //disposition of download forces a download
echo $filedata;
// die();
} //of While
} //try
catch (PDOException $e) {
$error = '<br>Database ERROR fetching requested file.';
echo $error;
die();
} //catch
} //isset
?>
This:
header("Content-length: strlen($filedata)");
Is not going to produce what you expect. If you look at the headers in wireshark, or another method to view the request you will see that it does not contain an integer.
Use this instead:
header("Content-length: ".strlen($filedata));
After agonizing over fixing it in-place (that is, on the same page with the rest of the html and code), I decided to move it to a dedicated PHP page. After that, it worked fine.
Thanks for the comments!
here is good example and complete source
My application sends urlencoded or base64encoded string via http get request, the string contain image data, that most be download from the php file, but i dont know how php would download image from my string that is either urlencoded or base64encoded, please help me out guys... im lost
Serve image to a user
// we assume $imageData is PNG
$image = urldecode($imageData);
// or
$image = base64_decode($imageData);
// in case of force download change Content-Type: image/png to
// application/octet-stream and Content-Disposition: inline to attachment
header('Content-type: image/png');
header('Content-Disposition: inline; filename=' . md5($image) . '.png');
header('Content-Length: ' . strlen($image));
echo $image;
exit;
The problem si to detect correct Content-Type if you don't know it. But browsers should be able to autodetect it on its own.
Some notes about caching
PHP implicitly sends headers which prevents browser caching of retrieved data. I suggest you to set these headers manually (Cache-Control, Expires, Pragma). To work properly, every single image must be served by an unique URL. Also try to avoid of starting sessions. On heavily accessed website with public access you can easily flood webserver with redundant session files.
Save image to a file
$image = urlencode($imageData);
// or
$image = base64_decode($imageData);
if (!file_put_contents('abs/path/to/save/file.png', $image)) {
throw new Exception('Image could not be saved');
}
I'm having a stump with some PHP...
I have a Flash Application that sends an image (using as3corelib) to a PHP script that previews it in the browser, which works! But, I would actually like it to permanently save it the a server folder (uploads, etc.) instead of temporarily saving it. I can't find the right variable in the PHP that actually sends the image to a server so it could save it.
<?php
switch ($_POST["format"]) {
case 'jpg':
header('Content-Type: image/jpeg');
break;
case 'png':
header('Content-Type: image/png');
break;
}
if ($_POST['action'] == 'prompt') {
header("Content-Disposition: attachment; filename=" . $_POST['fileName']);
}
echo base64_decode($_POST["image"]);
?>
Here's an example of it: http://shmoggo.com/snapshot
JPEG, Open to Browser (but I would like it to SAVE to browser)
Any PHP guru help would be terrific, thanks a lot!
Aaron
If you have the filename, you can simply do
$newpath = "/folders/image.jpg";
$data = file_get_contents($_POST['fileName']);
file_put_contents($newpath, $data);
Rather then displaying it, save $_POST['image'] to the server, see File System