I am trying to display img_a.png or img_b.png based on the access level of the user (e.g. signed in or not). Of course the content (in this case img_a and img_b) should not be available to the general public.
I tried a few solutions, none of them helps me and that's why I look for help here. What I tried so far is:
Based on the user checks I tried adding the resources folder to "open_basedir" which is a lame option but was looking the easiest solution. All ended up by raising a warning that resource is not in the basedir folder through it's obviously there.
Attempted to put the resources in the public folder and restrict them via .htaccess. But in this case they got restricted not only for the unwanted audience but for everyone.
Final and closest attempt was to put back the images outside the webroot and write a class that validates the access and serves the image like:
class Image {
...
public function getImage() {
...
header('Content-Type: '.$this->type);
readfile($this->item);
which afterwards is displayed in the initial script through:
echo "<img src=".$image->getImage($file).">";
The problem above is that the headers were already sent so I could either stream the image or the html output of the .php page but not both. Do I have a way out there?
Create a script that checks whatever user attribute you want, determines what image to serve, and read/send that image. Use the script URL as the <img src=... attribute, ie
<img src='/scripts/user_image.php'>
Something like this will work for PNG images. Similar functions exist for GIF, JPG, etc.
<?php
// do stuff here to determine file name of image to send
if($_SESSION['userlevel']=="ADMIN"){
$imageFilename="admin_image.png";
}
// Create Image From Existing File
$image = imagecreatefrompng($imageFilename);
//Set the Content Type
header('Content-type: image/png');
// Send Image to Browser
imagepng($image);
// Clear Memory
imagedestroy($image);
exit;
?>
OK, per your comment, I think you are referencing things wrong.
My working script is exact as above, only the if-then is commented out. I'm just assigning the filename to the variable. I've named the script user_image.php.
A simple index.html file to reference the image -
<html>
<head><title>test</title></head>
<body>
Hello World!<br />
<img src="user_image.php">
</body>
</html>
And it Just Works. See it in action at https://itsjustcrap.com/img or grab source at https://itsjustcrap.com/img/src.zip
I'll leave it up for a few days, but other than a png image and a commented out if-then, the source is exact same as what is in this post.
Actually I think I found a solution to the headers confict I had.
Displaying the image as data like:
<img src="data:image/png;base64, <?=base64_encode(file_get_contents($file))?>" alt="img">
instead of feeding it inside the source attribute with readfile() php script like:
<img src="image.php?<?=$file?>" alt="my_image">
where the last one was giving me a headers conflict when inside html page.
Discovered the solution over here How to display Base64 images in HTML?
Related
I am trying to read multiple image files from a folder (.htaccess protected) and display in a HTML page using php readfile().
The problem is I can see only the first image is read and the next is not shown in the browser. The code is as below
<?php
$image1 = 'files/com_download\256\50\www\res\icon\android\icon-36-ldpi.png';
$image2 = 'files/com_download\256\50\www\res\icon\android\icon-48-mdpi.png';
$imginfo = getimagesize($image1);
header("Content-type: ".$imginfo['mime']);
readfile($image1);
$imginfo = getimagesize($image2);
header("Content-type: ".$imginfo['mime']);
readfile($image2);
?>
I could see the first image 'icon-36-ldpi.png' successfully read and displayed in the browser and the second image is not read and not displayed in the browser.
Am I missing something? Any advice please.
Sorry if I am doing stupid but the requirement is to read multiple image files and render in the browser like a grid view. I cannot use img tag because of security reasons.
You can't dump both images out at once. Why not make two images in your html so the browser makes two calls to your script. Then use a GET param to pass the filename you want to display.
---Edit---
Important Security Note
There is an attack vector which you open up when doing soething like this. Someone could easily view your source html and change the parameter to get your image script to output any file they want. They could even use "../../" to go up directories and search for well known files that exist. e.g. "../../../wp_config.php". Now the attacker has your wordpress database credentials. The correct way to prevent against this is to always validate the input parameter properly. For example, only output if the file name ends with ".jpg"
How can I create a php code that will process an ID for example and return corresponding image without providing client with actual image hotlink.
As implemented on link below the image is displayed in html page, but the hot link is hidden from client. Even opening the image in new window same link is shown not the original link to image.
This is definitely not implemented in .htaccess file as for each image URL with id corresponding image is rendered and is not a redirect to a single page.
http://www.imagesup.net/?di=15140291437113
a basic way could be something like this
<?php
// query to database mabye?
$myPath = getImagePath($_GET['id']);
// what kind of image file is that?
$contentType = getContentType($myPath);
// read file content
$img = file_get_contents($myPath);
// here you tell the browser what kind of image is that e.g. jpeg,png,gif...
header("Content-Type: $contentType");
echo $img;
?>
you need to define getImagePath and getContentType functions according to your needs.
Whenever a surfer enters one of my websites, I always assign a session to him. The session holds a couple infos, for example: agent, IP, language, date, … etc., and gets passed along via cookie or via GET (as parameter to each one of my pages).
Since I deal with a lot of image content, I started databasing my collection. Which basically means that for administration and clustering purposes, I am saving all my images to a SQL database which is multi-homed and spread accross several servers. One could argue if that is a smart thing to do, but we can argue that on another day and in another article.
I wrote a little script which is used throughout my site:
<img src="http://example.com/display.php?id=34" border="0" alt="" />
With an ever changing ID of course. That’s the part referencing my images in the database.
The following is the code from the script which I use to retrieve the image from the database:
<?php
$connection=#mysql_connect(...);
#mysql_select_db(...);
$query="SELECT mime, file FROM images
WHERE id=".$_GET["id"];
$rawdb=#mysql_query ($query,$connection);
if($rawdb AND #mysql_num_rows($rawd-->0){
$array=# mysql_fetch_array($result);
if (!empty($array["fileContents"])){
// Output the MIME header
header("Content-Type: ".$array["mime"]}");
// Output the image
echo $array["file"];
}else{
// something else...
}
#mysql_free_result($rawdb);
}else{
// something else...
}
#mysql_close($connection);
?>
Since I already have a session for each user that comes to my website, I just added the following:
<img src="http://example.com/display.php?id=34&sid=383829" border="0" alt="" />
And implement a small session checkup in the script itself:
<!--
session_start();
if($_SESSION["is_known"]){
// do database calls
}else{
header("Location:http://mydomain.tld/dontsteal.html");
}
-->
The main advantage to my method is, that the session is entirely server side. A user can not rid himself off it, or fake information. Since I have a timeout and save all the necessary info (IP!) to validate against, it looks pretty perfect to me and fit my needs.
One of the setbacks here are resources and performance. But since I am not forcing you, you may test and evaluate. Hope that helps!
Create a php script which you use as src in the img tag.
In that script get the data from the image with file_get_contents. Then send the header with the right mime type. For example header('Content-type: image/jpeg'); Then output the data.
This is an odd question but I'm stuck on how I would achieve this and I am unable to find any methods of doing so.
I have a simple php script that takes variables (containing file names) from the URL, cleans then and then uses them to generate a single image from the inputted values. This works fine and outputs a new png to the webpage using:
imagepng($img);
I also have a facebook sharing script in PHP that takes a filepath as an input and then shares the image on the users feed where this statement is used to define the image variable:
$photo = './mypic.png'; // Path to the photo on the local filesystem
I don't know how I can link these two together though. I would like to use my generation script as the image to share.
Can anyone point me in the right direction of how to do this? I am not the master of PHP so go easy please.
-Tim
UPDATE
If it helps, here are the links to the two pages on my website containing the outputs. They are very ruff mind you:
The php script generating the image:
http://the8bitman.herobo.com/Download/download.php?face=a.png&color=b.png&hat=c.png
The html page with the img tag:
http://the8bitman.herobo.com/Share.html
Treat it as a simple image:
<img src="http://yourserve/yourscript.php?onlyImage=1" />
yourscript.php
if($_GET['onlyimage']) {
header('Content-type:image/png'); //or your image content type
//print only image
} else {
//print image and text too
}
Hi I have searched the web for 2 days but did not accomplish what I am looking for.
I have an apache server which will be accessed by 146 students. the user picks an angle from dropdown lets say 45 degress, then user clicks CALCULATE button. Then user clicks DIAGRAM button to see how the sine graph looks like.
Works like charm when i write the image to a file e.g: imagepng($img,"diagram.png");
Now the problem is that the diagram.png will always get overwritten by the last user. So for example if another user logs in and calculates the Sin 135. Both users will see Sine 135 because filename is hardcoded since there is conflict of filename.
I have searched the web on how to create the image dynamically instead of writing to a file and then reading the file. I have come across the following but not working:
base64_encode and decode
What would I have to do to my code of imagepng(...., ...) mentioned above to make use of base64 so I can actually draw the picture of already processed data. Let assume if I comment out the imagepng(..) code, then what do I replace it with. I hope I don't have to change my code a whole lot.
Please help
thanks
Amit
The filename argument to imagepng is optional. From the manual:
filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
You would just need to send a png header at the top of the script and you would get the image as output for that script.
It's hard to tell without seeing you code how it is structured
but if once the user submits the form all you do is show the image by itself, then you can do something like this.
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
If you embed the image into an html page as the result, then your best best would be to change the url of the image on the success page to something like this.
<img src="/path/to/file.php?deg=45" />
Then in the file.php
$deg = $_GET['deg'] + 0; // make sure it is a number
$img= function_render_graph($deg);
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
By using a GET request, rather then a POST request then the image will likely be cached by the browser, so it doesn't need to be rendered each time. (Given that you have a drop list of angles, there must be a limited number of graphs that can actually be drawn)
Draw_Resultant_Prism_Graph (parameters)
{
$img = imagecreatetruecolor(800,750);
....
....
...
the following lines captures the data from output buffer and displays on same screen
***some version of IE have some issues mostly the dumb terminals where IE update is ADMIN
***restricted
ob_start();
header("Content-type: image/jpeg");
imagepng($img);
$output = ob_get_contents();
ob_end_clean();
imagedestroy($img);
echo img src="data:image/jpeg;base64,'.base64_encode($output).'"
user tags around img above and semicolon af
}
I would like to generate a dynamic image from a script, and then have it load to the browser without being persistent on the server.
However, I cannot call this by setting the image's src="script.php", since that would require running the script that just generated the page and its data all over again, just to get the final data that will generate the graph.
Is there a way to do this that is similar to setting image's src="script.php", but which is called from within another script, and just sends the image without saving it? I need access to the data that is used in the generation of the markup, in order to create this dynamic image.
Or, if not, what is the easiest way to destroy the image once the page is loaded? a quick ajax call?
Is there any way to cache certain data for some limited time frame in order for it to be available to some other script?
Any ideas would be greatly appreciated, as I'm having a really hard time finding the right solution to this...
Thanks!
You can inline the image into a <img> tag if you need to.
Like
<?php
$final_image_data; // Your image data, generated by GD
$base64_data = base64_encode($final_image_data);
echo "<img src=\"data:image/png;base64,{$base64_data}\" ... />";
?>
That should work on all modern browsers, and IE8. Doesn't work well with some email clients tho (Outlook, for one).
Also, another solution I found is to store the image in a session variable which is then called from a php script in the image tag. This would allow a user specific image to be served, and then removed from memory by the script... This also avoids messy img src="" tags...
Hopefully that is helpful to someone.
Use a rewrite rule.
RewriteRule ^magicimage.jpg$ /myscript.php
Then simply echo your image data from gd, instead of writing it to disk -- which is as simple as not providing a filename to the appropriate image*() function
myscript.php
<?php
$im = imagecreatetruecolor($w, $h);
//...do gd stuff...
header('Content-type: image/jpeg');
//this outputs the content directly to the browser
//without creating a temporary file or anything
imagejpeg($im);
And finally, utilize the above
display.php
<img src="magicimage.jpg">