由文件下载引起的

来源:互联网 发布:苏州大学网络接入认证 编辑:程序博客网 时间:2024/04/29 23:57
 初级版:
php提供了内置的函数,可以使用readfile() 来实现文件的直接输出.
readfile('1.mp3');

提高版:
你可以打开allow_url_fopen来输出外部的文件.
readfile('http://xxx/1.mp3');
但是如果你想用FTP的话,就需要这样做:
readfile(ftp_get($conn_id, $local_file, $server_file, FTP_BINARY));

中级版:
手册中有这么一句:
Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Reference CL, Stream Functions.

并且,偶想实现盗链.所以有了使用stream的代码
$context=array('http' => array ('header'=> 'Referer: http://xxxxxxx/'));
$xcontext = stream_context_create($context);
readfile('http://localhost/1.mp3',0,$xcontext);

这些代码运行的也不错.

高级版:
下面要做的就是断点续传的php实现.具体你怎么取得range,是你自己的事情.

$context=array('http' => array ('header'=> 'Range: bytes=1024-'));
$xcontext = stream_context_create($context);
readfile('http://localhost/1.mp3',0,$xcontext);

注意!不对了!

在调试了许多次后,发现php并不支持除200外的任何返回值.
偶向php提交了偶的bug报告.
http://bugs.php.net/bug.php?id=36857

欣慰的是,1天后得到了这样的消息,就算偶给php做了点小小的贡献...
This bug has been fixed in CVS.

(另:最喜欢看这句: Thank you for the report, and for helping us make PHP better.)


- Fixed bug #36857 (Added support for partial content fetching to the HTTP streams wrapper). (Ilia)
(Bug #36857 was fixed,bringing support for partial content fetching to the HTTP streams wrapper across all current PHP branches [Ilia])

参见:#36857

这样,你现在可以使用这段代码了(版本要求 4.X: >4.4.3RC1 5.X:>5.1.3)

终极版A:
$file = fsockopen("www.xxxx.com", 80, $errno, $errstr, 12);
fputs($file, "GET /xxxxxx HTTP/1.0/r/n");
fputs($file, "Host: www.xxxx.com/r/n");
fputs($file, "Referer: http://xxxxx//r/n");
fputs($file, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)/r/n/r/n");

做完这些工作,你可以把这文件当普通文件用了.够简单吧...

终极版B:cURL
<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
这东西效率比纯粹的方法高不少.
由于它不是核心自带的东西,所以不做过多讨论
原创粉丝点击