.htaccess文件停止使用直接URL访问pic

时间:2016-03-16 09:32:17

标签: php .htaccess codeigniter

我在php和CodeIgniter有一个网站,用户上传他们的个人资料照片,个人资料照片存储在名为pic_uid.jpg的文件夹中。

然后我的脚本从同一文件夹加载图片。

我想停止使用.htaccess文件直接访问图片。

如果pic路径是

http://localhost/myweb/uploads/users/pic_19.jpg

如果有人输入此直接路径,他将无法访问pic,但当我的脚本调用此图片时,他可以访问并显示图片。

我尝试了很多选项,但是当我停止访问目录时,我的脚本也无法加载图片。

如何实现这一目标?

由于

2 个答案:

答案 0 :(得分:2)

你可以这样做。有一个目录说secured。在该目录中,放置此.htaccess

Deny From All

现在,将所有图像文件存储在那里:

+ secured/
  - image-1.png
  - image-2.png
  - image-3.png

在PHP脚本中,使用此代理:

<?php
  ob_start();
  /* true if the conditions met, like coming from the script or something */
  $right_user = true or false;
  if ($right_user) {
    header("Content-type: image/png");
    echo file_get_contents("secured/" . $_GET["file"]);
    die();
  } else {
    header("Content-type: text/plain");
    die("Ha ha! Can't steal!");
  }

为了重申我所做的一切,我在Cloud9创建了一个回购。在那,我有这些文件:

└── php
    ├── index.php
    ├── insecure.php
    └── secured
        ├── .htaccess
        └── hello.txt

每个文件都是这样的:

<强> insecure.php

<?php
    header("Content-type: text/plain");
    if (file_exists("secured/" . $_GET["file"]))
        echo file_get_contents("secured/" . $_GET["file"]);
    else
        echo "404! File Not Found.";
    die();
?>

<强> secured/.htaccess

Deny From All

<强> secured/hello.txt

Hello, World.
I am not accessible through normal requests.
My location is in /php/secured/hello.txt.

<强>演示

  

注意: 我在免费帐户,因此服务器只运行一段时间。请使用它。

答案 1 :(得分:0)

用于使用直接URL停止访问pic 使用codeiginiter的URI 在routes.php中复制此代码

$route['uploads/users/(:any)'] = "page_not_found";

此代码阻止访问文件夹上传/用户

的所有网址