如何在html中显示图像,同时限制对这些图像的访问


How display image in html while limit access to those?

我的问题是当你使用示例:

<img src="/img.jpg" />

src必须是一个图像,并且该图像必须可供个人访问。我希望能够控制对这些图像的访问(例如,如果用户已登录)。如果这个人不能访问图像,他就不能访问它。我控制访问图像的脚本是一个php文件。

我知道.htaccess可以限制对资源的访问,但我需要在php文件中有效。有没有办法做到这一点,或者用javascript加载图像(使用ajax请求),并将图像的源更改为临时文件夹中图像的位置?

您的图像源不必指向真实图像,也不必是图像:

<img src="images.php?f=img.jpg" />

然后,您可以编写一个PHP脚本来进行所需的验证,然后通过脚本返回图像

$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');
}
$image = basename($_GET['image']);
if (validation()) {
    header('Content-type: image/jpeg');
    readfile($image);
} else {
    header('HTTP/1.1 403 Forbidden');
}

basename是强制性的,因为黑客会把每个密码都存储在你的服务器上
正确的内容类型
正常内存消耗

<img src="/image.php?id=myImage.jpg">

和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);
}
?>

使用PHP提供图像

如果PHP正在输出图像内容,则可以使用PHP限制访问。

通过使用src标记http://www.example.com,您没有使用PHP,您的web服务器正在自行提供图像。

要使用PHP输出图像,请确保适当地设置了头变量。

例如:

<?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');
}
?>

您可以使用PHP来完成此操作。。。有关示例,请参见imagejpeg。。。然后就有了如下的img

<img src="/myfile.php" />

或者使用您的PHP文件获取图像并使用输出

header('Content-Type: image/jpg');
echo file_get_contents("yourimage.jpg");

您可以在$_SESSION中查看user_login_status,并在视图部分检查它的

<?if ($_SESSION['user_status'] == 'login'){?>
  <img src="/img.jpg" />
<?}else{?>
  // some stuff instead of <img/>
<?}?>