Friday, 7 March 2014

 

HOW TO DOWNLOAD FILE IN PHP?

                   
                                                                                                  Rahul R 
                                                                                                                        rahul9629@gmail.com
------------------------------------------------------------------------------------------------------------------------------------

HTML SECTION WITH LINK FOR DOWNLOAD FILE

<html>
    <head>
        <title>Download File</title>
    </head>
    <body>
        <!--Link For Downloading Resume -->
        <a href="download.php?doc=coding stds in brief.doc">Download</a> 
    </body>
</html>

 

PHP SECTION FOR DOWNLOAD

<?php


if(isset($_REQUEST['doc']))
   
     // change the path to fit your websites document structure 
     $path = "uploads/";
   
    //Getting filename and seeting the path like uploads/coding stds in brief.doc
    $fullPath = $path.$_GET['doc'];  


    if ($fd = fopen ($fullPath, "r"))
    {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);
        switch ($ext)
        {
            case "pdf":
            header("Content-type: application/pdf"); // add here more headers for diff. extensions
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
            break;
            default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        }
        header("Content-length: $fsize");
        header("Cache-control: private"); //use this to open files directly
        while(!feof($fd))
        {
        $buffer = fread($fd, 2048);
        echo $buffer;
        }
    }
    fclose ($fd);
    exit;
}
?>

No comments:

Post a Comment