<?php
$file = $_GET['file'] ?? '';
$path = realpath(__DIR__ . '/' . $file);

// جلوگیری از خروج از مسیر
if (!$path || strpos($path, realpath(__DIR__)) !== 0) {
    die("دسترسی غیرمجاز");
}

$size = filesize($path);
$basename = basename($path);
$range = null;

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$basename\"");
header("Accept-Ranges: bytes");

if (isset($_SERVER['HTTP_RANGE'])) {
    preg_match('/bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $matches);
    $start = intval($matches[1]);
    $end = $matches[2] !== '' ? intval($matches[2]) : $size - 1;

    header("HTTP/1.1 206 Partial Content");
    header("Content-Range: bytes $start-$end/$size");
    header("Content-Length: " . ($end - $start + 1));

    $fp = fopen($path, "rb");
    fseek($fp, $start);

    while (!feof($fp) && ftell($fp) <= $end) {
        echo fread($fp, 1024 * 8);
        flush();
    }
    fclose($fp);
    exit;
}

header("Content-Length: $size");
readfile($path);
exit;
