How to hidden the img source IP? - php

I have a img label embed a image path of mine public server, and show the image to users:
<img src="http://13.43.68.1:8000/img/gen/trafiic.png">
but this is security risk, because users can get my image source server(13.43.68.1).
So, is there any method to let users can not get the IP? such as cache the image data, just show the cached img data as src.
Edit-01
I am under the image.tpl, smarty template of PHP:
<div class="panel-body text-center">
<h4>Daily</h4>
<img width="360" src="http://13.43.68.1:8000/img/gen/trafiic.png.php?switch={$switch}&port={$portname}&cycle=-1d"><br><br>
<h4>Weekly</h4>
<img width="360" src="http://13.43.68.1:8000/img/gen/trafiic.png.php?switch={$switch}&port={$portname}&cycle=-1w"><br><br>
<h4>Monthly</h4>
<img width="360" src="http://13.43.68.1:8000/img/gen/trafiic.png.php?switch={$switch}&port={$portname}&cycle=-1m"><br><br>
</div>
in this case, how to hidden the src IP?

I'd say your IP being exposed is not particularly a security flaw. You can get the IP address of any server whether its backed by a hostname or not. I'd recommend purchasing a domain name (or mapping the subdomain of an existing domain) and pointing it using an A record to your image servers IP address.
You'd then be able to access your images by going to http://fakedomain.com:8000/img/gen/trafiic.png for example.
While you could convert all of your images to base64 and output them that way, your source code will grow - it's better to keep separate requests :)
Alternatives:
use a middle man such as Cloudflare to prevent exposing your IP address
base64 - but wouldn't recommend as its expensive on page load (but then depends on your needs)
use a script to generate and offload your graphs to somewhere like Amazon S3 and load from there.

If the source gives the image URL to you, you can get URL content and encode it in base64. Check the code below:
$imgURL = 'https://via.placeholder.com/350x150';
$imageData = file_get_contents($imgURL);
$imgSrc = 'data:image/png;base64,' . base64_encode($imageData);
return '<img src="'.$imgSrc.'">';

you could use this solution to convert your image to base64 and decode the base64 as src instead of using url

Related

How to show image hidding its direct link in php?

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.

Can I use PHP in a email signature?

I have a question. I would like to add rotating links inside my email signature to
track results on my site. I can make these dynamic tracking urls on google as you may know
but I would like to rotate them inside my email signature to see which text draws the most
conversions or returning visitors.
Is this possible?
I found this for instance:
$mybanners[1] = '<img src="banner1.jpg">';
$mybanners[2] = '<img src="banner1.jpg">';
$id = rand(1,2);
echo $mybanners[$id];
But when I look into my windows live mail I can only upload html files.
Does someone know how to do this?
You can't provide PHP scripts in a mail, since it is a server-side language and it will be opened by a mail client. Even Javascript is very often blocked for security reason.
What you can do is make a "fake" image which will be in fact generate by a PHP script. YOu can find inspiration by looking to script made for forum avatar rotation. The idea is to generate an image, which will be displayed to the client but, in the same time, save some data about the user who requests the image if you want:
<?php
// Save whatever you want about the user
file_put_content("log/user.txt", $_SERVER['HTTP_REFERER']);
// Render a valid PNG image
header('Content-Type: image/png');
readfile("/path/to/banner.png");
?>
This script should be used as a standard image (with, if you want, a nice URL rewrite to make a .png link):
<img src="http://www.example.com/my_super_banner.php" />
where my_super_banner.php is the script described before.

Display user input image without saving it to a folder

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

PHP: Storing picture in the file directory, image name in db and retrieving an image

After doing research, I found that it is more recommended to save the image name in database and the actual image in a file directory. Two of the few reasons is that it is more safer and the pictures load a lot quicker. But I don't really get the point of doing this procedure because every time I retrieve the pictures with the firebug tool i can find out the picture path in the file directory which can lead to potential breach.
Am I doing this correctly or it is not suppose to show the complete file directory path of the image?
PHP for saving image into database
$images = retrieve_images();
insert_images_into_database($images);
function retrieve_images()
{
$images = explode(',', $_GET['i']);
return $images;
}
function insert_images_into_database($images)
{
if(!$images) //There were no images to return
return false;
$pdo = get_database_connection();
foreach($images as $image)
{
$path = Configuration::getUploadUrlPath('medium', 'target');
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ( ? )";
$prepared = $pdo->prepare($sql);
$prepared->execute(array($image));
echo ('<div><img src="'. $path . $image . '" /></div>');
}
}
One method to achieve what you originally intended to do by storing images in database is still continue to serve image via a PHP script, thus:
Shielding your users from knowing the actual path of an image.
You can, and should have, images stored outside of your DocumentRoot, so that they are not able to be served by web server.
Here's one way you can achieve that through readfile():
<?php
// image.php
// Translating file_id to image path and filename
$path = getPathFromFileID($_GET['file_id']);
$image = getImageNameFromFileID($_GET['file_id']);
// Actual full path to the image file
// Hopefully outside of DocumentRoot
$file = $path.$image;
if (userHasPermission()) {
readfile($file);
}
else {
// Better if you are actually outputting an image instead of echoing text
// So that the MIME type remains compatible
echo "You do not have the permission to load the image";
}
exit;
You can then serve the image by using standard HTML:
<img src="image.php?file_id=XXXXX">
You can use .htaccess to protect your images.
See here:
http://michael.theirwinfamily.net/articles/csshtml/protecting-images-using-php-and-htaccess
I'm also working on a project which stores the url path of images on the database (Amazon RDS) and the actual images in a cloud managed file system in Amazon S3.
The decision to do so came primarily with the concern of price, scalability and ease of implementation.
Cheaper: Firstly, it is cheaper to store data in a file system (Amazon S3) compared to a database (Amazon EC2 / RDS).
Scalable: And since the repository of images may grow pretty big in the future, you might also need to ensure that you have the adequate capacity to serve them. On this point, it is easier to scale up a filesystem compared to a database. In fact, if you are using cloud storage (like Amazon S3), you don't even need to worry about having not enough space as it has been managed for you by Amazon! you would just need to pay for what you use.
Ease of Implementation: In terms of implementation, storing images in a file system is much easier. If you were to serve images directly from databases, you would probably need to implement additional logic to convert blob files into html src blob strings to serve images. And from the look of it, this might actually take up quite substantial processing power which might slow your web server down.
On the other hand, if you were to use a filesystem, all you would require is to put down the url path of the image from the database to the src attribute of the image and its all done!
Security: As for security of the images, i have changed the image name to a timestamp concatenated with a random string so that it will prove really difficult for someone to browse for pictures without knowing the file name.
ie. 1342772480UexbblEY7Xj3Q4VtZ.png
Hope this helps!
NB: Please edit my post if you find anything wrong here! this is just my opinion and everyone is welcome to edit!

How to display an Image from a mysql blob

I am trying to display an image from a MySQL blob field. I have tried a few different things and none of them seem to work.
I have tried:
header("Content-type: $type"); img src = $blobData;
header("Content-type: $type"); echo($blobData);
<?php
header("Content-type: $type");
echo $blobData;
?>
This code looks perfectly OK. However, I heard a similar complain from another person and I was able to troubleshoot it by assuring that:
The php script does not output any extra character before or after sending the binary image data.
The php script is saved as a pure ASCII text file, not as a Unicode/UTF-8 encoded file. The Unicode/UTF-8 encoded PHP files might include a signature as the first bytes. These bytes will be invisible in your text editor but server will send these few extra bytes to the browser before the JPEG/GIF/PNG data. The browser will therefore find the wrong signature in the beginning of data. To workaround, create a blank text file in notepad, paste in the php code and save the file in ANSI encoding.
Another option you might consider (assuming you are on Apache):
Create an .htaccess file with a mod_rewrite for all image extensions (png, jpg, gif).
Have it redirect to a php script that looks up the image requested in the DB. If it is there, it echos out the header and BLOG. If it isn't there, it returns a standard 404.
This way you can have:
<img src="adorablepuppy.jpg" />
Which then gets redirected ala:
RewriteEngine on
RewriteRule \.(gif|jpg|png)$ imagelookup.php
This script does a query for the image, which (obviously) assumes that the requested image has a unique key that matches the filename in the URL:
$url = $_SERVER['REQUEST_URI'];
$url_parts = explode("/", $url);
$image_name = array_pop($url_parts);
Now you have just the image filename. Do the query (which I shall leave up to you, along with any validation methods and checks for real files at the address, etc.).
If it comes up with results:
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename="adorablepuppy.jpg"');
print($image_blog);
otherwise:
header("HTTP/1.0 404 Not Found");
FYI: I have no idea if this would be bad in terms of performance. But it would allow you to do what I think you want, which is output the image as though it were a flat image file on the server using a simple image element. I'm inclined to agree that BLOBs are not the best way to go, but this does avoid any cross-browser issues.
I believe that the issue that you are encountering is an issue with encoding. This resource claims that you can use the print function.
Just get the image from the database. And print it using the correct headers.
$image = mysql_fetch_array(...)
header("Content-type: image/jpeg"); // change it to the right extension
print $image['data'];
For performance reasons... this is not advisable. There are several reasons to put images in databases but the most common are:
a) keeping them indexed (duh!)
You can do this by storing the images flat on the server and just indexing the image filename.
b) keeping the image hidden/protected
Flickr and alike still store the images flat on the server and use a different approach. They generate a URL thats hard to find.
This link points to a protected image on my account. You can still access it once you know the correct URL. Try it!
farm2.static - a farm optimized for delivering static content
1399 - perhaps the server
862145282 - my username
bf83f25865_b - the image
In order to find all my secret images any user can hard hit Flickr with the above address and change the last part. But it would take ages and the user would probably be blocked for hammering the server with thousands of 404s.
That said there is little reason to store images on BLOBs.
Edit:Just a link pointing to someone that explained much better than I did why BLOB is not the way to go when storing images.

Categories