(一)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//上传文件尺寸最大值
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- PHP 5.3.0 安装分析心得
- apache 环境下 php 的配置注意事项
- ASP.NET、ASP、PHP、JSP之间有什么区别?
- PHP VBS JS 函数 对照表
- C语言实现的统计php代码行数功能源码(支持文件夹、多目录)
- php xml 入门学习资料