您的位置:首页 > 编程语言 > PHP开发

(一)PHP学习笔记系列之(文件操作) //待完善

2015-09-23 11:11 537 查看

1、文件下载和上传技术

(1) file_get_contents()函数:打开本地/远程文件内容



代码:
//远程得到url内容,不下载

$timeout = 20;

$opts = array(

'http' => array(

'method' => "GET",

'header' => 'Content-Type:text/html; charset = utf-8',

'timeout' => $timeout, //设置超时

)

);

$context = stream_context_create($opts);

$url = "http://curl.dangdang.com/lx.txt";

//         $url = "http://www.baidu.com";

$file_content = @file_get_contents($url, false, $context,2,10);

echo $file_content;


分析:读取远程服务器上文件内容,2/10表示从第3个字节开始读取10个字节内容。服务器需要配置nginx指定域名请求。

(2) header()函数:打开本地/远程文件



代码:

$filename = "http://curl.dangdang.com/lx.txt";
header("Content-type: application/octet-stream");
//      header("Content-Type: application/text");
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header("Content-Length: ". filesize($filename));
readfile($filename);


分析:header()函数应该是模拟发送一个HTTP请求。

转载:鸟哥的一篇博文讲述了文件名中文时怎么做,和直接让webserver按文件发送给用户,让PHP提供更快文件下载

(3) curl_()函数:远程下载文件*

//从
4000
远程服务器上下载文件,比如lx.txt,配置服务器nginx。



set_time_limit(0);

$url = "http://curl.dangdang.com/lxv2.php";
$pi = pathinfo($url);
$ext = $pi['extension'];
$name = $pi['filename'];

//    var_dump($ext,$name,$pi['dirname'],$pi['basename']);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$opt = curl_exec($ch);
curl_close($ch);

$saveFile = $name.'.'.$ext;
if (preg_match("/[^0-9a-z._-]/i", $saveFile)) {
$saveFile = md5(microtime(true)).'.'.$ext;
}

$handle = fopen($saveFile, 'wb');
fwrite($handle, $opt);
fclose($handle);


分析:初始化一个session,再curl下载文件,在本地新建一个同名文件并写入内容,即下载过程。

(4) 文件上传技术

上传技术需要注意php.ini配置文件的上传配置参数:

file_uploads = On//上传开关

upload_max_filesize = 2M//上传文件尺寸最大值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php