saving an image from the browser issue - php

I'm using code to print an image without showing the real path for it. But I have a problem when I want to save that image to my computer because its always show the PHP file name as the name for the image.
$id = intval($_REQUEST["id"]);
$getimage = $db->query("select id,img from bbup where id='$id'");
$fetch_image = $db->fetch($getimage);
$filename = $fetch_image['img'];
if (!$id) {
echo "Wrong Id";
exit;
}
if (!file_exists($filename)) {
echo "Image not found.";
exit;
}
$aaa = SITE_URL . $filename;
$imginfo = getimagesize($aaa);
header("Content-type: " . $imginfo['mime']);
readfile($aaa);
The php file is ppupload.php and when I want to save the image (let's say it is a PNG image) in the dialog box the name of the file show ( ppupload.php.png ) and I want it to be the image itself.
The image path stored into the database like this: folder/folder/filename.ext.

Have you tried setting the Content Disposition header?
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Type: application/octet-stream');
This might help.

You can try to add something like this header("Content-Disposition: inline; filename=\"myimg.png\"");

Related

Download differnt type of files using the same code PHP

I am trying to download files from server and it works fine for pdf files, I am wondering is there a way to download any type of files such as doc, zip,.. etc.
My code:
<?php
$doc = $sqlite->readDoc($documentId);
if ($doc != null) {
header("Content-Type:" . $doc['mime_type']);
header('Content-disposition: attachment; filename="something"');
print $doc['doc'];
} else {
echo 'Error occured while downloading the file';
}
?>
You'll want to identify the file - maybe using this function:
http://php.net/manual/en/function.mime-content-type.php
and then you can create a switch to indicate the content-type and appropriate disposition. There's a decent example here: PHP - send file to user
A simple function that can be used to download any file formate form path.
function DownloadFile($strFilePath)
{
$strContents = file_get_contents(realpath($strFilePath));
if (strpos($strFilePath,"\\") > -1 )
$strFileName = substr($strFilePath,strrpos($strFilePath,"\\")+1);
else
$strFileName = substr($strFilePath,strrpos($strFilePath,"/")+1);
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"${strFileName}\"");
echo $strContents;
}
Usage Example
$file = $_GET['file_id'];
$path = "../uploads/".$file; // change the path to fit your websites document structure
DownloadFile($path);

Cant upload and store the image to the database by using php

I try to build an upload image system by using php.After testing it,the system echo out"Image is uploaded",but it doesn't shown in database.Here is my code here
upload.php
<?php
//connect database
include('config.php');
//file properties
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
if(!isset($file)){
echo "Please select an image";
}
else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name =addslashes($_FILES['image']['name']);
$image_size =getimagesize($_FILES['image']['tmp_name']);
if ($image_size == FALSE) {
echo "This is not an image";
}
else{
$insert = "INSERT INTO image(name,picture) VALUES ('$image_name','$image')";
if(!$insert){
echo "Problem uploading";
}
else {
$lastid =mysqli_insert_id($con);
echo "Image Uploaded <p />Your Image :<p /><img src=get.php?id=$lastid>";
}
}
}
?>
get.php
<?php
include ('config.php');
$id = addslashes($_REQUEST['id']);
$image = mysqli_query($con ,"SELECT * FROM image WHERE id=$id");
$image = mysqli_fetch_assoc($image);
$image = $image['picture'];
header("Content-type :image/jpeg");
?>
and I clicking the submit button without choosing any files this 2 line of warning is showing up
Warning: file_get_contents(): Filename cannot be empty in upload.php line 14.
line14 is this $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Warning: getimagesize(): Filename cannot be empty in in upload.php line 16.
while line 16 is this $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Any idea about this?
You need a function to send your query, otherwise you just filled up a string: this:
$insert = "INSERT INTO image(name,picture) VALUES ('$image_name','$image')";
should be followed by this:
mysqli_query($con, $insert);
The warnings are caused by multiple issues with your code. First you are checking whether the file has been uploaded in the wrong way: this
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
Will always set a $file variable, even though no file has been selected into the form, leading therefore to never execute this if statement:
if(!isset($file)){
echo "Please select an image";
}
and to always execute what's in the else block instead, which causes the errors, because the functions you mentioned, which are contained in this else block, are not able to operate on any file.
Therefore simply checking the file upload correctly will solve the issue: one way to do this would be to first remove this, which is unuseful
if(isset($_FILES['image'])){
$file = $_FILES['image']['tmp_name'];
}
and then change this:
if(!isset($file)){
echo "Please select an image";
}
to this:
if(!isset($_FILES['image']['tmp_name'])){
echo "Please select an image";
}
After line 16 you need to echo the image data.
echo $image;
#ken, here is a function that I use to output the image by setting the correct headers:
function output_headers($filetype, $imgsize, $filename, $attachment=false)
{
header("Content-Type: {$filetype}");
header("Pragma: public");
header("Cache-Control: public");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 * 24 * 4 -1;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr);
header("Cache-Control: max-age=$offset");
//header("Content-Type: application/octet-stream");
header('Accept-Ranges: bytes');
header("Content-Length: $imgsize");
#insert the filename we want into the image so it can be saved with something
# more meaningful that showimg.jpg. :-)
# 04/03/06
#attachment causes save as to appear, inline serves imbedded image.
if ($attachment)
header('Content-Disposition: attachment; filename="' . $filename . '"');
else
header('Content-Disposition: inline; filename="' . $filename . '"');
}
This is part of a php file called showimg.php.jpg
This needs to be saved into a separate directory with the following .htaccess file to get php to handle requests for .jpgs:
AddType application/x-httpd-php .jpg
In this way, the webpage refers to the image <img src='/img/showimg.php.jpg?<add your parameters here>
regards
Steve

PHP output image issues

if (file_exists($path)) {
$fileContent = id3_getImage($path);
$fileMime = id3_getMimeOfImage($path); // is set to image/jpeg
if ($fileMime != "") {
header('Content-Type: '.$fileMime);
print($fileContent);
die;
}
}
So the above code does not work in the browser, however when I make a image with image
$img = imagecreatefromstring($fileContent);
imagejpeg($img, 'test.jpg');die;
the image is created and I can view it on my computer. So I have no clue what I am doing wrong :(
*Could it be a setting in the apache conf? I honestly have no clue on this one
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($img);
You need send header before. But if you want to create the image and show, you need create, and read this for the browser.
readfile($filename);
You can read the man here:
http://php.net/manual/en/function.readfile.php
I use smartReadFile.php from Google Groups to display any type of file.
https://jplayer.googlegroups.com/attach/f308294ddea52f6c/smartReadFile.php?view=1&part=4
It's really smart. =)
<?php
require "smartReadFile.php";
$dir = 'images/';
$filename = 'someimage' . '.jpg';
$location = $dir.$filename;
smartReadFile($location, $filename);
?>
This one is working for me when reading from DB
$image = imagecreatefromstring([path/DBfiels]);
header('content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);

retrieving files from database by their path

I have a simple html form, that saves the email message and multiple attachments path. I am saving the files on the server and their path to the database filed.
Now how can i retrive the files from its path, and then show them to user, when click on Download, I am using the following code for getting the file, but this is not working
$query = "
SELECT `type`, `name`, `size`, `file1`,`file2`,`file3`,`file4`,`file5`
FROM `upload` WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
header("Content-Type: ". $row['type']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
$path = $row['file1'];
$dir = opendir($path);
echo $dir;
while ($dir && ($file = readdir($dir)) !== false) {
echo $file;
}
The echoed file doesnot contain any data.
This i am doing now for only one file, whose path is at "file1". Similarly i have 5 attachments path, and i have to retrive them all in this code.
Please how can i do it.
First: You can't have more than one download like this. You can only send that header once and that's it.
Is $path the full path to the file? You could try is_readable($file) to check first in a test. Once you have the full path though, it's simple.
header("Content-Type: application/octet-stream");
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
readfile($row['file1']);
exit();
Readfile outputs directly and streams it, so you don't have to read the content in and then output it. Add the exit to make sure no other output get's added after it, or you could corrupt the file.
This works, assuming $row['file1'] has a correct path!
For multiple files, you have to make multiple calls. Like give the user mutliple links they can click on for downloads.
The only alternative is that you pack it together using zip for example, and send it as one large zipfile.

uploading an image from flash using php more specifically HTTP_RAW_POST_DATA?

I currently have it working so it displays a dialogue box to save the image on your computer:
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;
}
just wondered if there is any way to put the file straight into a directory/file without the need of a dialogue box?
like an uploader?
No, there is not.
Just Read the content of the page and save in a file using fopen , fwrite e.t.c.
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
// get bytearray
$jpg = $GLOBALS["HTTP_RAW_POST_DATA"];
// add headers for download dialog-box
ob_start();
header('Content-Type: image/jpeg');
echo $jpg;
$image=ob_get_clean();
//and here write it into file
}
OR following is my code you can remove unneccessary things that are not useful for you
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
$filename=$_GET['name'];
$fullFilePath='files/'.$filename;
$handle=fopen($fullFilePath,"w");
fwrite($handle,$im);
fclose($handle);
$returnVars = array();
$returnVars['write'] = "yes";
$returnString = http_build_query($returnVars);
//send variables back to Flash
echo $returnString;
}

Categories