在PHP中隐藏远程文件的真实下载地址,可以通过以下方法实现,既能保护资源路径,又能防止直接盗链

以下是具体实现方案及代码示例:

function SecureDownload($url,$fileName){
   // 获取文件大小(推荐方法二选一)
   try {
       // 方法1get_headers
       $headers = get_headers($url, true);
       $fileSize = $headers['Content-Length'] ?? new Exception("未找到文件大小");

       // 方法2cURL(若方法1失效)
       // $fileSize = getRemoteFileSizeCurl($url);
   } catch (Exception $e) {
       // 备用方案:下载前1MB验证
       $context = stream_context_create(['http' => ['header' => 'Range: bytes=0-10240']]);
       $partial = file_get_contents($url, false, $context);
       $fileSize = strlen($partial);
   }

   // 设置响应头
   header('Content-Transfer-Encoding: binary');
   header('Content-Type: audio/*');
   header('Content-Length: ' . $fileSize);
   header('Content-Disposition: attachment; filename="'.rawurlencode($fileName).'"; filename*=UTF-8\'\''.$fileName);
   header('Cache-Control: no-cache');
   ob_clean();
   flush();

   // 流式输出(避免内存溢出)
   $chunkSize = 1024 * 1024; // 1MB分块
   $handle = fopen($url, 'rb');
   while (!feof($handle)) {
       echo fread($handle, $chunkSize);
       ob_flush();
       flush();
   }
   fclose($handle);
}

在PHP中实现隐藏本地下载地址并显示文件大小,需结合路径隐藏技术与文件信息获取方法。以下是具体实现方案及代码示例:


function secureDownload($filePath, $displayName) {
           // 验证文件存在性
           if (!file_exists($filePath)) {
               header("HTTP/1.0 404 Not Found");
               exit;
           }

           // 获取文件信息
           $fileSize = filesize($filePath);
           $mimeType = mime_content_type($filePath);

           // 设置HTTP
           header('Content-Description: File Transfer');
           header('Content-Type: ' . $mimeType);
           header('Content-Disposition: attachment; filename="' . rawurlencode($displayName) . '"');
           header('Content-Length: ' . $fileSize);
           header('Expires: 0');
           header('Cache-Control: must-revalidate');
           header('Pragma: public');

           // 流式输出优化内存
           $chunkSize = 1024 * 1024; // 1MB分块
           $handle = fopen($filePath, 'rb');
           while (!feof($handle)) {
               echo fread($handle, $chunkSize);
               ob_flush();
               flush();
           }
           fclose($handle);
           exit;
}

       // 使用示例
  $realPath = '/secret/files/report.pdf'; // 真实路径不暴露
  $fakeName = 'quarterly_report_2023.pdf'; // 展示给用户的文件名
  secureDownload($realPath, $fakeName);