PHP: Grab an image from a stream (in an img tag) but if it's not there, i don't want the img tag written. How?
I currently have code like this in a web based file called 'view_file.php' to grab an image from an internal network.
<img src="put_file.php?type=<?=$TN_TYPE;?>&path=<?=$TN_PATH;?>&filename=<?=$TN_FILENAME;?>" />
The 'put_file.php' script allows access to an internal server that we don't want to expose to the internet. This scr开发者_如何学Cipt checks to see if an image is available and if it is, sends an image header and then uses readfile()
to stream the image to the 'view_file.php' page.
The problem is if there isn't an image available, instead of streaming a temporary 'spacer.gif' i want to not have the img tag written at all.
Any Ideas how to do this? I'm thinking maybe move the img tag into the 'put_file.php' script, but how to mix strings and steams?
Can't be done simply I think.
You could make a call to
put_file.php
in PHP, see what it returns, and if it returns an empty value (or a404
header or whatever) refrain from writing the img tag. Obvious con: The request is made twice, and it complicates the script.You could create the image element in JavaScript depending on the result of an Ajax call to
put_file.php
. Obvious con: Doesn't show up straight after loading, and needs JavaScript.
Both these options could be reduced to making one request by piping the results of the testing request into base64-encoded data:
URI's, but that is highly incompatible (no IE support) and bloats the page on browser side (the image data plus 33% overhead would be present straight in the source code, or the JavaScript memory, respectively). I wouldn't recommend it.
If at all possible, I personally would stick with the spacer.gif
solution.
Update: One other idea, if it's just that you don't want the images to appear, would be sending a 404
header when the image isn't there, and utilizing the onerror
event of the img
tag to, say, do a <img onerror='this.style.display = "none"'>
. Requires Javascript, of course. The error event seems to be fully supported in all browsers (reference here, german only sorry, but you'll see the icons :).
You can use base64 to do what you want.
http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
精彩评论