PHP download hidden file real address path method

Method 1, use the fread() function to slice and download, which is suitable for large-volume downloads. Speed ​​limit download is possible, but it is easy to cause memory overflow and download failure.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

public function fileUrl($url)

{

    $file 'uploads/files/'.$url;

    if (file_exists(\dirname(__FILE__).$file)) {

        return $this->error("文件不存在");

    }

    // 新文件名

    $filename explode('.'$file);

    $filename array_pop($filename);

    $filename = time().'.'.$filename;

    //下载文件

    $filesize filesize($file) + 1000;

    header('Content-Description:File Transfer');

    header("Content-Type:application/octet-stream");

    header('Content-Transfer-Encoding:binary');

    header("Accept-Ranges: bytes");

    header('Expires:0');

    header('Cache-Control:must-revalidate');

    header('Pragma:public');

    header("Content-Length:".$filesize);

    header("Content-Disposition:attachment;filename=".$filename);

    $fp fopen($file"rb"); 

    fseek($fp,0); 

    while (!feof($fp)) { 

        set_time_limit(0); 

        print (fread($fp, 1024 * 8)); 

        flush(); 

        ob_flush(); 

    

    fclose($fp); 

    exit ();

}

Method 2, downloading with no speed limit, no slicing, and no limit, is suitable for downloading small files.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public function fileUrl2($url)

{

    $file 'uploads/files/'.$url;

    if (file_exists(\dirname(__FILE__).$file)) {

        return $this->error("文件不存在");

    }

    // 新文件名

    $filename explode('.'$file);

    $filename array_pop($filename);

    $filename = time().'.'.$filename;

     

    header('Content-type:application/octet-stream');

    header('Content-Disposition:attachment;filename='.$filename);

    header('Content-Length:'.filesize($file));

    readfile($file);

}

Guess you like

Origin blog.csdn.net/winkexin/article/details/131150212