Sending an image in my php form, it gets saved onto my server and at the
action.php page it gets displayed. Now when I try to:
echo '<div id="image"><img src="'.$target_path.'" width="280" height="280"></div>';
it works just fine... but if I add unlink($target_path); at the end of my php code it
will not even display the image even though it gets deleted AFTER displaying the image...
So the question is, how can I display the image and deleting it at the same time so my server does not gets stuffed with user pictures?
Try another thing: output the image base-64 encoded.
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
echo '<div id="image"><img src="data:image/jpg;base64,'.$base64.'" width="280" height="280"></div>';
(instead of move_uploaded_file() etc, use as $file variable the $_FILES[...]['tmp_name'])
You can achieve this by creating a little script that gets the image-filename and will delete it after it has been retrieved:
<?php
$file = image_file_from_parameter($_GET['image']);
headers_for_file($file);
readfile($file);
unlink($file);
In your HTML output you then link to that script:
<img src="path/to/image.php?image=893sudfD983D" />
If you set nice caching headers, the user won't notice that your server did serve the file only once.
When you echo the url of an image with img src you're just sending the browser the url of an image, not the actual image data. The image needs to remain on the server if you want it to be viewable by this approach.
You could use bwoebi's solution to pass the actual image data instead of a link, but a better solution is just to keep the images on the server and periodically delete old files.
Related
How can I display an image and pass it as an input parameter in an executable in php without saving the image in a folder. The user gives the image path as input and I am using ajax to display the image when it is selected when I save it to a folder it works but how can I display it without saving it in a folder? My code now is
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
//echo "Stored in "."upload/".$_FILES["file"]["name"];
echo "<img src='upload/".$_FILES["file"]["name"]."' class='preview'>";
I tried
<img src=$_FILES["file"]["tmp_name"]. class='preview'>
but it didnt work. As I will have thousands of input from thousands of user I dont want to save it. Is there any optimised and efficient method to do this?
I think, its not possible to show image without saving it. You could try to save the image in temp folder on the server side and clean this folder periodically to avoid much space consumption.
The src attribute of the <img> tag should be an URL accessible by the client.
You try to give a local path (ex: path/to/your/file.jpg) of a temporary file as URL, it will not working.
info: The uploaded image is save on the local disk on a temp directory, and could be deleted by PHP later.
If you want to show the image without moving it at a place reacheable by a URL, you can try to load its content as base64 content
$imagedata = file_get_contents($_FILES["file"]["tmp_name"]);
$base64 = base64_encode($imagedata);
and use in your HTML
<img src="data:image/png;base64, <?php echo $base64; ?>" />
I don't think you can show the image without saving it.
You need to save the file either to the filesystem or to memory if you want to later output
Your problem here is that $_FILES only exists in the script that the image was sent to. so when you initiate another http request for img source, php no longer has any clue what file your trying to read.
You need a way to tell which image to be read on http request.
One thing you can do is that you can save the file in a place accessible by the client and then just have php delete it after you output it. So once the image is outputted it will be deleted and no longer be existing in the file system.
Another approach would be to get the image from the memory by directly writing the contents to httpresponse.
You can do this way
$image = file_get_contents($_FILES["file"]["tmp_name"]);
$enocoded_data = base64_encode($image);
and when you show your image tag :
<img src="data:image/png;base64, <?php echo $enocoded_data ; ?>" />
Hope any of these helps you
Let's say I have a user enter the URL of an image.
After URL validation, etc. I want to get the image and store it in a PHP variable. Not the image path, but the actual image itself.
I am adding this image-holding variable in between other strings, so I cannot change use header() before echoing the image. Is it possible to use <img> HTML tags? I really don't want to copy the images to my own server...
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
Edit:
I said above that I am putting this image inside another variable, e.g.:
$str = "blah blah" . $var_holding_img . "more text";
Is it possible to insert something in the string above that will be replaced with the images? Can parse the variable $str later to replace some random text like "abg30j-as" with the image...
I found an answer to my own question:
First, I created another PHP file, called img.php:
<?php
$url = $_GET['imgurl'];
/*
Conduct image verification, etc.
*/
$img_ext = get_ext($url); //Create function "get_ext()" that gets file extension
header('Content-type: image/' . $img_ext);
echo file_get_contents($url);
?>
Then, in the original PHP file, I used this PHP code:
<?php
$var_holding_img = '<img src="img.php?imgurl=http://example.com/image.png"/>';
$string = "This is an image:<br \>" . $var_holding_img . "<br \>displayed dynamically with PHP.";
echo $string;
?>
This way, the PHP file "img.php" can use the proper headers and the image can be inserted as HTML into any other PHP variable.
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
You can do this in two ways.
In way one, you serialize the image in a string, and save the string in the session. Which is exactly the same as saving it server side, except that now the session GC should take care of clearing it for you. Then the IMG SRC you use will redirect to a script that takes the image and outputs it as image with proper MIME type.
In way two, if the image is small enough, you can encode it as BASE64 and output it into a specially crafted IMG tag:
http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
This saves you some time in connection, also. Of course the image must be reasonably small.
You can't save the actual image in a variable. Either you save the URL or copy the image (what you obvious don't want) to your server and save the path to the image
See answer 1, you can't echo the image itself, only link it
Edit: Okay obviously you can save images directly to a variable, but I don't recommend you to do this.
No, that isn't possible. If you want to serve something, it has to exist on the server.
I have been having a hard time with what must be an incredibly normal task. I upload and save images to my web server and save the path to the file in MySQL data base (this is all working). The thing that doesn't work is fetching an image file from the server and displaying it on the page via ajax.
Originally I was trying to just retrieve the path from the database, and update an tag's src attribute with the path to the image. This was working, but this way all the images are in a folder on the server where people all have access to them. This is not good. I can only have the pictures that belong to certain users accessible by these users.
In order to restrict access to these photos I added an Apache directive on that folder, which successfully restricted access. The problem then became that I could not display the images in the browser by setting the src attribute to that path. See my post: https://serverfault.com/questions/425974/apache-deny-access-to-images-folder-but-still-able-to-display-via-img-on-site
Finally I have learned that I have to use PHP to read the image data directly from the server and send this data to the browser. I have used the file_get_contents() function, which works to convert the image file (PNG) on the server into a string. I return this string to the browser in an ajax call. The thing I can't get is: how to convert this string back into an image using JavaScript?
See this code:
$.ajax({
url: get_image.php,
success: function(image_string){
//how to load this image string from file_get_contents to the browser??
}
});
You could display a default "no access" image to users who are forbidden to access the image:
<?php
$file = $_GET['file']; // don't forget to sanitize this!
header('Content-type: image/png');
if (user_is_allowed_to_access($file)) {
readfile($file);
}
else {
readfile('some/default/file.png');
}
And, on the client side:
<img src="script.php?file=path/to/file.png" />
Alternatively, if you really really want or need to send the data via Ajax, you can Base64 encode it:
<?php
echo base64_encode(file_get_contents($file));
And place the response in an img tag using the Data URI scheme
var img = '<img src="data:image/png;base64,'+ server_reponse +'"/>';
Given that the Base64 encoded data is significantly larger than the original, you could send the raw data and encode it in the browser using a library.
Does that make sense to you?
Instead of getting get_image.php through AJAX, why not just use:
<img src="get_image.php" />
It's practically the same thing. You can just use AJAX to update the <img> dynamically.
You can't do it via ajax.
You could do something like this:
<img src="script.php?image=image_name" />
Then use JavaScript to change the query string.
You can actually embed image data inside the img tag in the browser, therefore ajax code could look like this:
$.ajax({
url: get_image.php,
success: function(image_string){
$(document.body).append("<img src='data:image/gif;base64," + base64_encode(image_string) + "' />);
}
});
Note that you will need to write this base64_encode function. Have a look at this question - the function is given there.
I need to send a GET request to my page pic.php, and I want to get a real picture in return.
For now I implemented this idea like this:
<?php
if ((isset($_GET['pic']))&&(isset($_GET['key']))){
$pic = $_GET['pic'];
$pic=stripslashes($pic);
header('Location: /content/'.$pic);
}
?>
But it's not really what I want - it redirects to image directly. What I want is to keep the same URL, but get a needed file depending on what values were submitted.
What is the best way to do that?
thx.
This example code snippet should do what you ask. I've also included code to only strip slashes if magic quotes is enabled on the server. This will make your code more portable, and compatible with future versions of PHP. I also added use of getimagesize() to detect the MIME type so that you output the proper headers for the image, and do not have to assume it is of a specific type.
<?php
if(isset($_GET['pic']))
{
//Only strip slashes if magic quotes is enabled.
$pic = (get_magic_quotes_gpc()) ? stripslashes($_GET['pic']) : $_GET['pic'];
//Change this to the correct path for your file on the server.
$pic = '/your/path/to/real/image/location/'.$pic;
//This will get info about the image, including the mime type.
//The function is called getimagesize(), which is misleading
//because it does much more than that.
$size = getimagesize($pic);
//Now that you know the mime type, include it in the header.
header('Content-type: '.$size['mime']);
//Read the image and send it directly to the output.
readfile($pic);
}
?>
I can see you doing this in two ways:
1) Return the URL to the image, and print out an image tag:
print '<img src=' . $img_url . ' />';
2) Alternatively, you could just pull the data for the image, and display it. For instance, set the header appropriately, and then just print the image data.
header("content-type: image/png");
print $img_data;
This assumes that you have the image data stored in a string $img_data. This method will also prevent you from displaying other things on the page. You can only display the image.
You can load the image, send the image headers, and display the image as such:
header('Content-Type: image/jpeg');
readfile('/path/to/content/pic.jpg');
Obviously the headers would depend on the filetype, but that's easy to make dynamic.
Not sure if I understand what you're after, but guessing that you want to load the picture in an img tag?
If I'm right you just do:
<img src=http://www.domain.com/pic.php?"<?php echo image here ?>" />
Basically you just make the source of the image the webpage you get directed to where the image is.
I stored it images in the database using an BLOB field (I'm using SQLite). Now I want to recover this image to a HTML page and show the images there.
I can retrieve the binary data from the image from the database, but what I can do to transform this data in an image and show in the page? Currently I want to show the images inside a field in a table.
You could abuse the data: protocol, but trust me, you don't want that if you can avoid it. Normally, you create a separate php-script that serves images, so in script 1:
<img src="/myimagescript.php?id=1234">
In myimagescript.php:
//get the data from the database somehow (mysql query et al.)
//let's assuma the data is in $data
header('Content-Type: image/jpeg');//alter for png/gif/etc.
echo $data;
#uscere90 is right, but an example might help (example of a PNG image):
<?php
header("Content-type: image/png");
echo $image_data;
?>
Typically this is done by creating a wrapper script or function that retrieves the BLOB and delivers it with the appropriate content headers to be used as an <img src=''>
Doing it this way also gives you the benefit of being able to deliver or not deliver the image based on other authentication factors determined by your PHP. If, for example, a user doesn't have permission to see an image, you can instead show some default or blocking image in its place.
// File getimg.php
// Retrieve the image blob specified by $_GET['imgid'] from the database
// Assuming your blob is now in the variable $image...
header("Content-type: image/jpeg");
// Just echo out the image data
echo $image;
exit();
Now in your html:
<img src='getimg.php?imgid=12345' alt='this is your img from the database' />
You can create a simple image.php page that queries your database, then prints out a content-type relevant to the image and vomits the binary data to screen. So, in your table, you'd have <img src=image.php?id=something />, and then you'd use that id in your image.php page to do your database lookup, retrieve the binary data, and print it to screen after printing the content-type header.
image.php:
<?php
header('Content-type: image/jpeg');
//DO SQL NINJA STUFF HERE
echo mysql_result($result,0,"file_content");
?>
There are two options I would say:
You create a script that returns the image data. The <img src="-field then calls that script.
You offer the data of the images directly via a data url.
Both have it's pros and cons. For the first solution you must create a new script for the images. The second method will bloat your page if the images are large.
As there are examples for the image script method already, here is some code fragment for data URIs:
<?php
function data_uri($content, $mime)
{
$base64 = base64_encode($content);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
<img src="<?php echo data_uri($content,'image/png'); ?>" />
You need to set the mime-type according to your image, image/png for PNG images, image/jpeg for JPG files etc., see here for a list.