Secure images failing - Codeigniter - php

My script pretty much works, however when I run a for loop it fails, in the view:
<?php foreach($pics as $index=>$pic){?>
<td class='Pictures'>
<center>
<?php
$piece = explode('/',$pic["ThumbImg"]);
$string = $piece[5];
?>
<img src='<?php echo base_url(); ?>index.php/Controller/getImage/<?php echo $string; ?>/1' width="100px">
</a>
Controller class - Get image function:
//function to protect images from being accessed directly by obfuscating the URL
function getImage($img_id,$type){
if($this->members->logged_in()){
//code to authenticate user goes here then...
//code to decide which type of file it is/thumb/full size image
if($type==1)
{
$url = $this->data['base_url'].'system/application/images/pic/thumbs/';
}else if($type==0){
$url = $this->data['base_url'].'system/application/images/pic/';
}
$filepath = $url.$img_id;
//send image to web browser.
header("Content-type: image/jpeg");
//get path
$img_handle = imagecreatefromjpeg($filepath) or die("");
//create and send
ImageJpeg($img_handle);
}
I suspect that this could be due to the headers being resent, if so how can I resolve this.
Cheers
Fixed the problem - used "Hotlinking"

You will basically only need to set the header information header("Content-type: image/jpeg") if you're loading the image from the database. But since you're loading it from a folder you might want to skip the php file and immediately fetch the image from the folder:
<img src='<?php echo base_url(); ?>img_folder/<?php echo $string; ?>/1'
width="100px">

Related

How to pass variable to PHP picture

Motivated by this post
https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form I want to display my images by
<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?>
<img src="/resources/php/showImage.php" >
where showImage.php is simply given by
<?php
header('Content-Type: image/jpeg');
readfile($pathToPicture);
?>
But how can I pass the variable $pathToPicture to showImage.php? I do not want to hard-code $pathToPictue into showImage.php.
Pass the path of image as get parameter to showImage.php script like.
<?php $pathToPicture = "server/www/images/imagexyz1823014719102714123.png"; ?>
<img src="/resources/php/showImage.php?pathToPicture=<?php echo $pathToPicture;?>" >
Here you can get passed variable from $_GET array:
<?php
header('Content-Type: image/jpeg');
readfile($_GET['pathToPicture']);
?>
I preferably suggest use of base64_encode and base64_decode for pathToPicture for this purpose. Also not expose the whole path of your images location openly like this. Have a look at below improved code
<?php $pathToPicture = "imagexyz1823014719102714123.png"; ?>
<img src="/resources/php/showImage.php?pathToPicture=<?php echo base64_encode($pathToPicture);?>" >
<?php
$location = "server/www/images/";
$image = !empty($_GET['pathToPicture']) ? base64_decode($_GET['pathToPicture']) : 'default.jpg';
// In case the image requested doesn't exist.
if (!file_exists($location.$image)) {
$image = 'default.jpg';
}
header('Content-Type: '.exif_imagetype($location.$image));
readfile($location.$image);
?>

Php display image from url into homepage

after no one answered at this question Php Rss feed use img in CDATA -> content:encoded i try to do something else solving this problem...
how can i load an image from a given url directly into my homepage?
<?php
$url = "...";
$image = file_get_contents("$url");
echo $image;
?>
*i don't want to save the image anywhere... just load the image from the url and show it in my own homepage.
Try this code,work fine on my machine.
<?php
$image = 'http://www.google.com/doodle4google/images/d4g_logo_global.jpg';
$imageData = base64_encode(file_get_contents($image));
echo '<img src="data:image/jpeg;base64,'.$imageData.'">';
?>
You are almost there. When you download the contents of the file you need to encode it to base64 if you do not plan to store it on server.
<?php
$url = '...';
$image = base64_encode(file_get_contents($url));
?>
Then you can display it:
<img src="data:image/x-icon;base64,<?= $image ?>">

RewriteRule a <img src=...> or other solution

I want my IP cam streaming on my website.
Since I have this piece of code but if you look at the source code, you'll see of course the complete data as user and pass. That is not the intention, I looked at RewriteRule option in .htaccess but don't know how to formulate, or maybe another solution to protect my user and pass data. Who can help me get out the thinking circle and gives a move in the right direction (or example).
<?php
$url = '123.456.7.890:1234';
$user = 'naam';
$pass = 'wachtwoord';
$cam = "http://$url/videostream.cgi?user=$user&pwd=$pass";
?>
<html>
<body>
...
<img name="main" id="main" border="0" width="640" height="480" src="<?php echo("$cam"); ?>">
...
</body>
</html>
If camera response you with image you can get it in PHP code and then add it to image src like base64 data.
For example
<?php
$url = '123.456.7.890:1234';
$user = 'naam';
$pass = 'wachtwoord';
$cam = "http://$url/videostream.cgi?user=$user&pwd=$pass";
$image = file_get_contents($cam); // Or use CURL
// Here you need to replace $type of your camera
$image_src = 'data:image/' . $type . ';base64,' . base64_encode($image);
?>
<html>
<body>
...
<img name="main" id="main" border="0"
width="640" height="480" src="<?php echo $image_src ?>">
...
</body>
</html>
You should use your server side to create a image.
Solution can be found here: Create Image From Url Any File Type
You can create a PHP file that outputs the image or something.
If you do that, you can load the image like this: <img src="http://domain.com/image.php?id=1">
Then in image.php, you can load from your DB, or whatever you like.
However, when you have the real image info, you can make a "fake" image as descriped in the link above.

PHP Image not showing in HTML using img element

Hello there i have a php file with the included:
The image shows properly when i access the PHP file, however when I try to show it in the HTML template, it shows as the little img with a crack in it, so basically saying "image not found"
<img src="http://konvictgaming.com/status.php?channel=blindsniper47">
is what i'm using to display it in the HTML template, however it just doesn't seem to want to show, I've tried searching with next to no results for my specific issue, although I'm certain I've probably searched the wrong title
adding code from the OP below
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
echo "<img src='$online' />";
} else {
echo "<img src='$offline' />";
}
The url is not an image, it is a webpage with the following content
<img src='offline.png' alt='Offline' />
Webpages cannot be displayed as images. You will need to edit the page to only transmit the actual image, with the correct http-headers.
You can probably find some help on this by googling for "php dynamic image".
Specify in the HTTP header that it's a PNG (or whatever) image!
(By default they are interpreted as text/html)
in your status.php file, where you output the markup of <img src=... change it to read as follows
$image = file_get_contents("offline.png");
header("Content-Type: image/png");
echo $image;
Which will send an actual image for the request instead of sending markup. markup is not valid src for an img tag.
UPDATE your code modified below.
$clientId = ''; // Register your application and get a client ID at http://www.twitch.tv/settings?section=applications
$online = 'online.png'; // Set online image here
$offline = 'offline.png'; // Set offline image here
$json_array = json_decode(file_get_contents('https://api.twitch.tv/kraken/streams/'.strtolower($channelName).'?client_id='.$clientId), true);
header("Content-Type: image/png");
$image = null;
if ($json_array['stream'] != NULL) {
$channelTitle = $json_array['stream']['channel']['display_name'];
$streamTitle = $json_array['stream']['channel']['status'];
$currentGame = $json_array['stream']['channel']['game'];
$image = file_get_contents($online);
} else {
$image = file_get_contents($offline);
}
echo $image;
I suppose you change the picture dynmaclly on this page.
Easiest way with least changes will just be using an iframe:
<iframe src="http://konvictgaming.com/status.php?channel=blindsniper47"> </iframe>

How to serve multiple images which reside above the www root within a single page?

I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">

Categories