How may I display an image without using any kind of HTML.
Let's say I have some protected images, which may only be shown to some users.
The protected image is in directory images/protected/NoOneCanViewMeDirectly.png
Then we have a PHP file in the directory images/ShowImage.php, which check if the user is permitted to view the image.
How may I display the image using PHP only.
If you're not sure what I mean this is how I want to display the image. http://gyazo.com/077e14bc824f5c8764dbb061a7ead058
The solution is not echo '<img src="images/protected/NoOneCanViewMeDirectly.png">';
You could just header out the image with the following syntax
header("Content-type: image/png");
echo file_get_contents(__DIR__."/images/protected/NoOneCanViewMeDirectly.png");
if (<here your logic to show file or not>)
$path = $_SERVER["DOCUMENT_ROOT"].<path_to_your_file>; // to get it correctly
$ext = explode(".", $path);
header("Content-Type: image/".array_pop($ext)); // correct MIME-type
header('Content-Length: ' . filesize($path)); // content length for most software
readfile($path); // send it
}
Note: 1. image/jpg is not correct MIME-type, use image/jpeg instead (additional check needed), 2. readlfile() is better than echo file_get_contents() for binary data, 3. always try to provide content length for browsers and other software
You can use imagepng to output png image to browser:
$im = imagecreatefrompng("images/protected/NoOneCanViewMeDirectly.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
Related
I've a file on a folder on disk I don't want to be visible from web browser
So i create an image.php file that take a file name and must 'do echo' to browser of the image.
Example:
mysite.com/image.php?name=selection.png
must show an image to the user into the browser.
Actually browser ask me to save.
I want to show it, not do ask to download...
i'm using this snippet
header("Content-Type: image/png");
header('Content-Length: ' . filesize($full_file_name));
header("Content-Disposition: inline; filename='$image'");
readfile($full_file_name);
exit(0);
if saved and opened, img is perfect. How to NOT ask to download it?
EDIT
Yes, i need something to use into image tag
Most of you are replying to my question telling me about image creation, but my question is all about different mode to tell to browser to show something and to ask to user to save something.
NO MORE REPLY ABOUT IMAGE CREATION - YOU'RE OFF-TOPIC !
Probably my question, my title, is not clear, but my question is simple:
- How to tell to browser to SHOW an image insted to ask user to save it
Image creation is working
Image usage via imag src is working
**But when user clicks on image, a new tab is opened with the images src as link, because I need to show full size image into browser.
In this situation browser ask me to save !
EDIT:
Removing
header("Content-Disposition: inline; filename='$image'");
doesn't change Firefox behaviour
try:
header("Content-type: image/png");
passthru("cat $full_file_name");
Be very careful with the passthru command if you're working with user input, since this function will execute anything you pass it.
https://www.php.net/manual/en/function.passthru.php
When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.
To do this, you'd have to base64 encode the image, then output the result. You could use a function like this:
<?php
/**
* Base64 encodes an image..
*
* #param [string] $filename [The path to the image on disk]
* #param [string] $filetype [The image file type, (jpeg, png, gif, ...)]
*/
function base64_encode_image($filename, $filetype)
{
if ($filename)
{
$imgBinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
And then output the result as the source of the image, like:
$image = base64_encode_image('...name of file', '... file type');
echo "<img src='$image' />';
EDIT: I think I got the wrong end of the stick here, but oh well!
You can use PHP's GD library.
in your image.php.
<?php
header('Content-type: image/png');
$file_name = $_GET['name'];
$gd = imagecreatefrompng($file_name);
imagepng($gd);
imagedestroy($gd);
?>
You could alternatively use PHP's imagepng:
imagepng — Output a PNG image to either the browser or a file
<?php
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
If your picture paths are stored in a database this method is okay. (I have exampled using MySQLi, adapt this to your Database API)
CREATE TABLE IF NOT EXISTS `PicturePath` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`Path` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;
--
INSERT INTO `PicturePath` (`ID`, `Path``) VALUES
(1, 'img/picture.png')
//End DB
// Start script
$PictureID = $_GET['Name'];
$Get_Picture = $Conn->prepare("SELECT PicturePath FROM pictures WHERE ID=?");
$Get_Picture->bind_param('i', $PictureID);
$Get_Picture->execute();
$Get_Picture->bind_result($Path);
$Get_Picture->close();
echo "<img src='$Path'></img>";
The above method is best if you are selecting images using URL Parameters
Otherwise:
$Picture = $_Get['Name'];
$Image = imagecreatefrompng($Picture);
header('Content-Type: image/png');
imagepng($Image);
might be the solution
Manual here:
http://php.net/manual/en/function.imagepng.php
Is it possible to use Luracast Restler to return an image? Something like calling:
http://myserver.com/api/users/002/avatar
to download a png?
It is possible to serve images with Restler.
You need to do the following in your API method
Set the content type header for the right image type (png, jpeg etc)
header("Content-Type: image/png");
echo the image content
Example
$im = imagecreatefrompng("test.png");
header('Content-Type: image/png');
imagepng($im); //this sends the image as the response
imagedestroy($im);
use exit or die to stop execution instead of the usual return result
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 am using popular timthumb.php to resize images. i am successfully able to change height and width of image but whenever i do "save as" by default it saves as php..
for example, if you try to save the image present at
http://www.binarymoon.co.uk/demo/timthumb-basic/timthumb.php?src=castle1.jpg&w=400 it saves as a file with extension php..
how do i force to save it as png/jpg? i know the mime type is image/jpg or image/png .... all i want is the image should save as png or jpg by default... kindly help
Timthumb doesn't have "save as" option (see this reply http://o7.no/biJTYD on the developer blog http://www.binarymoon.co.uk/2010/11/timthumb-hints-tips/). Timthumbs saves the processed image with the same format as the source image.
I succeded in forcing a "save as jpg" when source is "png" with the followingwork around (near line 742). You may arrange other conversions working on the if-then-else chain.
if(preg_match('/^image\/(?:jpg|jpeg)$/i', $mimeType)){
$imgType = 'jpg';
imagejpeg($canvas, $tempfile, $quality);
} else if(preg_match('/^image\/png$/i', $mimeType)){
// ***************WORKAROUND STARTS HERE****************
//$imgType = 'png';
//imagepng($canvas, $tempfile, floor($quality * 0.09));
$imgType = 'jpg';
imagejpeg($canvas, $tempfile, $quality);
Untested but you can add an extra header to line 1195 under:
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="' . basename($file) . '";');
i simply use timthumb.php from this URL http://timthumb.googlecode.com/svn/trunk/timthumb.php
and when i click on save as, default file name is "Imagename.php.jpeg". and can able to change name before ".jpeg". may this will help you.
i am using Firefox on ubuntu 10.4.
enjoy
i want to print a image by using a img tag which src is a php file, the script will also process some action at server scirpt. Anyone have an example code?
here is my test code but no effect
img.html
<img src="visitImg.php" />
visitImg.php
<?
header('Content-Type: image/jpeg');
echo "<img src=\"btn_search_eng.jpg\" />";
?>
Use readfile:
<?php
header('Content-Type: image/jpeg');
readfile('btn_search_eng.jpg');
?>
Directly from the php fpassthru docs:
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
exit;
?>
As an explanation, you need to pass the image data as output from the script, not html data. You can use other functions like fopen, readfile, etc etc etc
"<img src=\"btn_search_eng.jpg\" />" is not valid image data. You have to actually read the contents of btn_search_eng.jpg and echo them.
See here for the various ways to pass-through files in PHP.
UPDATE
what you can do without using include as said below in the comments:
try this:
<?
$img="example.gif";
header ('content-type: image/gif');
readfile($img);
?>
The above code is from this site
Original Answer
DON'T try this:
<?
header('Content-Type: image/jpeg');
include 'btn_search_eng.jpg'; // SECURITY issue for uploaded files!
?>
If you are going to use header('Content-Type: image/jpeg'); at the top of your script, then the output of your script had better be a JPEG image! In your current example, you are specifying an image content type and then providing HTML output.
What you're echoing is HTML, not the binary data needed to generate a JPEG image. To get that, you'll need to either read an external file or generate a file using PHP's image manipulation functions.
if you use base64 it would be
<?php
header('Content-Type: image/jpeg');
echo(base64_decode('BASE64ENCODEDCONTENT'));
?>