PHPزبان های برنامه نویسیکامپوننت / کتابخانهمتن باز

دانلود فایل از طریق کد PHP

کار با فایل ها در php

با استفاده از این فانکشن می توانید فایل های موجود در سایت (بصورت پیش فرض در شاخه files سایت) را روی سیستم کاربر دانلود کنید.


public static function DownloadFile($filename)
{
    // place this code inside a php file and call it f.e. "download.php"
    // SITE_ROOT is a Constant in Config file for site root path
   $path = SITE_ROOT."/files/";
    $fullPath = $path.$filename;
     
    if ($fd = fopen ($fullPath, "r")) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);
        switch ($ext) {
            case "pdf":
        // add here more headers for diff. extensions
           header("Content-type: application/pdf");
            header("Content-Disposition: attachment; 
        // use 'attachment' to force a download
            filename=\"".$path_parts["basename"]."\""); 
            break;
            default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".
                     $path_parts["basename"]."\"");
        }
        header("Content-length: $fsize");
            //use this to open files directly
       header("Cache-control: private");
        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }
    fclose ($fd);
    exit;
   

}

نظرات