开发者

protect users' file being accessed so only owner can access?

I am writing a web application in php where users can upload their own files or images, but how can I protect these files from bein开发者_如何学Cg accessed by others other than the owner. think of dropbox, what is the mechanism to protect those files, I have tried to search but don't get anything about this. any pointers or any link to tutorials would be very useful. thanks in advance.


If you are storing images and files as binary blobs in your database, then it is simply a matter of checking permissions against the logged in user before retrieving and displaying them from the database.

If you are storing them as regular files, what you need to do is store them above the document root of your website, where they are not publicly accessible on the web. Then to retrieve an image, after checking the correct ownership from your database (we don't know your architecture, so substitute however you have stored what belongs to whom), PHP can retrieve the file and send it to the browser with the correct headers.

For example, to display an image:

// Check permissions...
// If permissions OK:
$img = file_get_contents("/path/to/image.jpg");

// Send jpeg headers
header("Content-type: image/jpeg");
// Dump out the image data.
echo $img;
exit();

You can, for example, keep a database table of filenames matched with user IDs to keep track of who owns what.


The typical way to do this goes something like...

  • A file is uploaded
  • The file is moved to a directory that is not accessible from the internet
  • An ID is generated for the file and stored in the database

Then, users use the ID to request the file from the server.

For this purpose, you would have a script that queries the database for the file based on the ID, and would then check if the user has access to reading it. If the user has access, it would read the file and output it to the user's browser.

For example, to read a jpeg image in PHP:

<?php
header('Content-type: image/jpg');
readfile('/path/to/image.jpg');


use unique and special file names, and only present them to the disired user. you can alsso set a session in PHP and check if the session is correcvt to include a file. and use httacces tio redirect to the PHP.

<?
sessuion_start();
file_exists($_SESSION['specialkey']_$_GET['realfilename']){
include(/* include the file */); // or readfile
//or header location, but then the rteal URL will become visible
}else{
die('acces denied');
}

the specialkey is set in the PHP page making the display page, and is unique for evey file and is gained from DB. it's the fastest way I could ciomme up with.

you might olso want to store the files in a dir that is only accesable from PHP

edit instead of include you could use Jani Hartikainen method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜