Search code examples
phpzend-frameworkzend-routezend-controller

ZendFramework - How to protect confidential files uploaded in public/directory?


Some users uploads there confidential contract/agreement files which is stored in a directory /var/www/html/project/public/contract/<HERE_UNIQUE_FILES.pdf>.

But the problem is from google search or direct link any unauthorized user can open it and view/copy it.

How can i protect it, so that only my domain or allowed peers can only have access to this private directory?

Example:

class Application_Model_Uploader
{

  public static function mvUploadContract()
  {     
        /* Anyone from outside can access this path, but how to protect it? */
        $target_path = APPLICATION_PATH . "/../public/contract/";          
        $target_path = $target_path .  basename( $_FILES['contractfile']['name']);
        if(move_uploaded_file($_FILES['contractfile']['tmp_name'], $target_path)) 
        {
            $result = true;
        }else{
            $result = false;
        }
  }
}

Solution

  • Move the files out of the public directory and use PHP to stream them after authorizing the user.

    if (is_authorized($user)) {
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename='.basename($path_to_file_outside_public));
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($path_to_file_outside_public));
    
      readfile($path_to_file_outside_public);
    }