Search code examples
php.htaccessfile-sharing

How to give users temporary access to specific links?


I see people do it a lot, usually when embedding videos.

They have links with timestamps or something in GET values that allow the user temporary access to the file.

I currently just have my .htaccess file have Options -Indexes (Just so they can't access the directories at all. I know it doesn't help much though)

Should I possibly make a PHP script to store in sql db special ids matched with IPs with timestamp that expire 30 minutes later? I don't know if that'd be the most efficient way of going about this.

What would be the best way of going about doing this?


Solution

  • You can use a timestamp + a protection hash, example:

    When you create the link you do something like this:

    define('SECRET',"onlyknownbyyourserversidescipt");
    
    $now = time();
    $protect = md5($now.SECRET);
    
    $link = 'http://what.ever/?'.http_build_query(array('t'=>$now,'p'=>$protect));
    

    When the link is opened you check if the time match the protected

    if(md5($_GET['t'].SECRET) === $_GET['p']){
      //then you can check the time
      if(time()-$_GET['t'] > 30*60){
        header(..)
      }else{
       header(..)
      }
    }
    

    Nobody can fake the timestamp because nobody knows your secret