Reputation: 462
My problem is when you use for exemple :
<img src="/img.jpg" />
the src has to be an image and the image has to be accessible to the person. I want to be able to control the access to those image (if the user is logged for example). IF the person has not access to the image, he can't access it. My script that controls the access to an image is a php file.
I know .htaccess can limit access to ressources, but I need to valid in the php file. Is there a way to do this or to load the image with javascript (using ajax request) and changing the source of the image to the location of the image in the temp folder?
Upvotes: 0
Views: 333
Reputation: 38180
Your image source doesn't necessarily have to point to the real image, neither does it have to be an image:
<img src="images.php?f=img.jpg" />
Then you can write a PHP script which does the required validations and return the image afterwards through the script
$image = basename($_GET['f']);
if (user_has_access()) {
// You have to determine / send the appropriate MIME-type manually
header('content-type: image/jpg');
readfile($image);
} else {
header('HTTP/1.1 403 Forbidden');
}
Upvotes: 5
Reputation: 23311
You can limit access using with PHP, if the PHP is outputting the image contents.
By using the src tag http://www.example.com, you are not using PHP, your web server is serving up the image on its own.
To output an image with PHP, make sure you set your header variable appropriately.
For example:
<?php
if($user->isAuthenticated())
{
$image = imagecreatefromjpeg ($server_image_path);
header('Content-Type: image/jpeg');
imagejpeg($image, NULL, 75);
imagedestroy($image);
}
else
{
header('HTTP/1.1 403 Forbidden');
}
?>
Upvotes: 1
Reputation: 157839
$image = basename($_GET['image']);
if (validation()) {
header('Content-type: image/jpeg');
readfile($image);
} else {
header('HTTP/1.1 403 Forbidden');
}
basename is mandatory, of a hacker will have every password stored on your server.
correct content type
sane memory consumption
Upvotes: 2
Reputation: 5008
<img src="/image.php?id=myImage.jpg">
And myImage.jpg:
<?php
$imageName = $_GET['id'];
$ctype="image/jpg";
$extension = substring($imageName, strstr($imageName, '.'));
switch($extension) {
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
}
if (someValidation_here) {
header("Content-Type: $ctype");
$handle = fopen($imageName, "rb");
echo fread($handle, filesize($imageName));
fclose($handle);
}
?>
Upvotes: 1
Reputation: 1246
You can ceep user_login_status in your $_SESSION, and on a view part check it
<?if ($_SESSION['user_status'] == 'login'){?>
<img src="/img.jpg" />
<?}else{?>
// some stuff instead of <img/>
<?}?>
Upvotes: -1