Jump to content

Fortare Download Orice Tip De Fisier In Php


Recommended Posts

Posted

Poate ati avut nevoie vreodata ca aplicatia voastra sa permita download-ul unui fisier .pdf sau a unui fisier imagine fara insa a le incarca in pagina. (de exemplu un link spre o imagine o va deschide tot timpul in browser).

Iata si cum puteti sa fortati download-ul oricarui fisier cu ajutorul php-ului:

<?php

function dl_file($file){

  //First, see if the file exists
  if (!is_file($file)) { die("<b>404 Fisierul nu  fost gasit!</b>"); }

  //Scoatem informatii despre fisier
  $len = filesize($file);
  $filename = basename($file);
  $file_extension = strtolower(substr(strrchr($filename,"."),1));

  //Setam Content-Type-urile pentru  fisierul in cauza
  switch( $file_extension ) {
    case "pdf": $ctype="application/pdf"; break;
    case "exe": $ctype="application/octet-stream"; break;
    case "zip": $ctype="application/zip"; break;
    case "doc": $ctype="application/msword"; break;
    case "xls": $ctype="application/vnd.ms-excel"; break;
    case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpg"; break;
    case "mp3": $ctype="audio/mpeg"; break;
    case "wav": $ctype="audio/x-wav"; break;
    case "mpeg":
    case "mpg":
    case "mpe": $ctype="video/mpeg"; break;
    case "mov": $ctype="video/quicktime"; break;
    case "avi": $ctype="video/x-msvideo"; break;

    //urmatoarele tipuri de fisiere nu ar trebui sa poate fi downloadate (chestii sensibile ca fisierele php, etc)
    case "php":
    case "htm":
    case "html":
    case "txt": die("<b>Nu poate fi folosita pentru fisiere  cu estensia ". $file_extension ." !</b>"); break;

    default: $ctype="application/force-download";
  }

  //Scriem headerele
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Cache-Control: public");
  header("Content-Description: File Transfer");

  //Folosim Content-Type-ul din switch
  header("Content-Type: $ctype");

  //Fortam downloadul
  $header="Content-Disposition: attachment; filename=".$filename.";";
  header($header );
  header("Content-Transfer-Encoding: binary");
  header("Content-Length: ".$len);
  @readfile($file);
  exit;
}

?>[/code]

:pct2:

Te-ai inregistrat? Ne-ar placea sa te prezinti.

Cum pot sustine forumul?
Cumpara de la eMag folosind acest link.
--------------------
oG2BN9d.gifse1WdXd.gifQG6MtmI.gifRHYjDzD.gifG5p1wui.gif

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.