PHP中FTP相关函数小结


Posted in PHP onJuly 15, 2016

本文实例讲述了PHP中FTP相关函数。分享给大家供大家参考,具体如下:

<?php
set_time_limit(0);
//转存本地地址
define(
  'STORE_PATH',
  dirname(__FILE__) . '/../../../../temp_data/test/'
);
define('LIST_PATH', STORE_PATH . 'list/');
define('CHAPTER_PATH', LIST_PATH . 'chapter/');
define('DETAIL_PATH', LIST_PATH . 'detail/');
createFolder(STORE_PATH);
createFolder(LIST_PATH);
createFolder(CHAPTER_PATH);
createFolder(DETAIL_PATH);
$ftp_server = "ip";
$ftp_user = "anonymous";
$ftp_pass = "anonymous";
$conn_id = ftp_connect ( $ftp_server ) or die ( "Couldn't connect to $ftp_server" );
if (@ftp_login ( $conn_id, $ftp_user, $ftp_pass )) {
echo "Connected as $ftp_user@$ftp_server\n";
} else {
echo "Couldn't connect as $ftp_user\n";
}
ftp_pasv($conn_id, true);
/**
 * 创建文件并写入内容
 *
 * @param string $path   path/
 * @param string $fileName filename
 * @param string $data   content
 *
 * @return string 返回路径
 */
function createFile ($path, $fileName, $data)
{
  if (empty($data)) {
    return false;
  }
  file_put_contents($path . $fileName, $data);
  return $path . $fileName;
}
/**
 * 创建目录
 *
 * @param string $path path
 *
 * @return no
 */
function createFolder ($path)
{
  if (! file_exists($path)) {
    createFolder(dirname($path));
    if (mkdir($path, 0777)) {
      echo "\n dir not find ,make dir " . dirname($path) . " is ok!";
    } else {
      echo "\n dir not find ,make dir " . dirname($path) . " is fail!";
    }
  }
}
/**
 * 抓取电子书籍的类别
 *
 * @param string $xmlUrl    xml地址
 * @param string $saveFileName 文件名称
 *
 * @return string 返回路径
 */
function getClassXml ($conn_id,$categoryDir, $saveFileName = 'category.xml')
{
  //获取顶级栏目
$clist = getDirListFormFtp($conn_id, $categoryDir);
$itemTPL = '<Item><ID>%s</ID><Name>%s</Name></Item>';
$items='';
foreach ($clist as $key=>$value){
$items .=sprintf($itemTPL,$value['name'],$value['detail']);
}
$bodyTPL='<Tofo><Class>%s</Class></Tofo>';
$data = sprintf($bodyTPL,$items);
  echo "\n".createFile(STORE_PATH, $saveFileName, $data);
}
set_time_limit(0);
$start_time = time();
$bookCache=array();
$categoryDir = "\\tingshu\\web";
getClassXml($conn_id,$categoryDir);
//获取顶级栏目
$clist = getDirListFormFtp($conn_id, $categoryDir);
//获取二级栏目分类
foreach ($clist as $key=>$value){
$_secondCateoryDir = $categoryDir.'\\'.$value['name'];
$_secondCateorylist = getDirListFormFtp($conn_id, $_secondCateoryDir);
$listData='';
$listTPL='<Tofo><Class><ID>%s</ID><Name>%s</Name><Books>%s</Books></Class></Tofo>';
$items ='<Item><ID>%s</ID><Name>%s</Name></Item>';
$listItemString='';
//获取详细书籍章节列表
foreach ($_secondCateorylist as $key=>$book){
$listItemString.=sprintf($items,$book['name'], $book['detail']);
$_bookListDir = $_secondCateoryDir.'\\'.$book['name'];
$chapters = getBook($conn_id,$_bookListDir);
//生产book章节html
getBookofChapter ($book,$chapters);
//缓存bookid和章节信息
$bookCache[$book['name']] = array('category'=>$value['name'],'chapters'=>$chapters);
}
//生成二级栏目列表页
$listData = sprintf($listTPL, $value['name'], $value['detail'],$listItemString);
$list_save_path = $value['name'] . '.xml';
  echo "\n".createFile(LIST_PATH, $list_save_path, $listData);
}
$arrString = "<?php \n \$bookCache=".var_export($bookCache, true).";\n?>";
echo "\n建立缓存文件:".createFile(STORE_PATH, 'bookcache.php', $arrString);
/**
 * 抓取书籍章节信息
 *
 * @param array $bookIds 书籍章节信息
 *
 * @return boolean 返回是否抓取成功
 */
function getBookofChapter ($bookinfo,$chapters)
{
  if (! is_array($chapters)) {
    return false;
  }
  $bookData = '';
$bookTPL = '<Tofo><Books><ID>%s</ID><Name>%s</Name><Volumes>%s</Volumes></Books></Tofo>';
  $bookItemTPL='<Item><ID>%s</ID><Name>%s</Name></Item>';
  //<Play>%s</Play>
//<Download>%s</Download>
//,$item['downurl'],$item['downurl']
  $chapterString='';
foreach ($chapters as $key=>$item){
  $chapterString.=sprintf($bookItemTPL,$item['name'],$item['detail']);
  }
  //生成二级栏目列表页
$bookData = sprintf($bookTPL, $bookinfo['name'], $bookinfo['detail'],$chapterString);
 $book_chapter_save_path = $bookinfo['name'] . '.xml';
  if (! empty($bookData)) {
    echo "\n".createFile(CHAPTER_PATH, $book_chapter_save_path, $bookData);
  }
  return true;
}
function getBook($conn_id,$_bookListDir){
$chapter=array();
$buff = ftp_nlist ( $conn_id, $_bookListDir );
if(is_array($buff)){
$resourceArray = array();
foreach ($buff as $key=>$value){
if(strstr( $value, '.txt' )){
}else{
$resourcesName = str_replace($_bookListDir.'\\', "", $value);
$temp = preg_split ( '/\./',$resourcesName);
$resourceArray[trim($temp[0])]=$resourcesName;
}
}
foreach ($buff as $key=>$value){
if(strstr( $value, '.txt' )){
$name = trim(str_replace(".txt","",str_replace($_bookListDir.'\\', "", $value)));
$chapter[$name] = array (
'name' => $name,
'detail' => getFileContentsFormFtp ( $conn_id, $value ),
'downurl' =>$resourceArray[$name]
);
}
}
}
ksort($chapter , SORT_NUMERIC);
echo "\n";
var_dump('chapter index :'.implode(array_keys ($chapter), ','));
echo "\n";
return $chapter;
}
function getDirListFormFtp($conn_id, $categoryDir) {
$categoryArray = array ();
$dirs = getDirNameFormFtp ( $conn_id, $categoryDir );
//获取分类描述
foreach ( $dirs as $key => $value ) {
$path = $categoryDir . '\\' . $value . '.txt';
$categoryArray [] = array ('name' => $value, 'detail' => getFileContentsFormFtp ( $conn_id, $path ) );
}
return $categoryArray;
}
function getFileContentsFormFtp($conn_id, $server_file) {
$_tempFileName = STORE_PATH.'temp.tmp';
$content = '';
try {
if (ftp_get ( $conn_id, $_tempFileName, $server_file, FTP_ASCII )) {
$content = file_get_contents ( $_tempFileName );
}
} catch (Exception $e) {
var_dump('error timeout:-----');
global $ftp_server;
$conn_id = ftp_connect ( $ftp_server );
if (@ftp_login ( $conn_id, $ftp_user, $ftp_pass )) {
echo "Connected as $ftp_user@$ftp_server\n";
} else {
echo "Couldn't connect as $ftp_user\n";
}
ftp_pasv($conn_id, true);
if (ftp_get ( $conn_id, $_tempFileName, $server_file, FTP_ASCII )) {
$content = file_get_contents ( $_tempFileName );
}
}
$content = iconv ( "GBK", "UTF-8//IGNORE", trim($content) );
echo "\n";
var_dump('file name :'.$server_file.';content:'.$content);
return $content;
}
function getDirNameFormFtp($conn_id, $dirString) {
$buff = ftp_rawlist ( $conn_id, $dirString );
$dirs = array_filter ( $buff, "dirfilter" );
foreach ( $dirs as $key => $value ) {
$temp = preg_split ( '/<DIR>/', $value );
$dirs [$key] = trim ( $temp [1] );
}
asort($dirs , SORT_NUMERIC);
return $dirs;
}
function dirfilter($var) {
return (strstr ( $var, '<DIR>' ));
}
ftp_close ( $conn_id );

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php生成缩略图的类代码
Oct 02 PHP
php 表单数据的获取代码
Mar 10 PHP
PHP 函数call_user_func和call_user_func_array用法详解
Mar 02 PHP
CodeIgniter输出中文乱码的两种解决办法
Jun 12 PHP
ThinkPHP3.1新特性之动态设置自动完成及自动验证示例代码
Jun 23 PHP
php判断GIF图片是否为动画的方法
Sep 04 PHP
PHP通过插入mysql数据来实现多机互锁实例
Nov 05 PHP
微信公众平台实现获取用户OpenID的方法
Apr 15 PHP
Android App中DrawerLayout抽屉效果的菜单编写实例
Mar 21 PHP
详解PHP原生DOM对象操作XML的方法
Oct 17 PHP
php安装php_rar扩展实现rar文件读取和解压的方法
Nov 17 PHP
PHP实现基本留言板功能原理与步骤详解
Mar 26 PHP
Yii数据模型中rules类验证器用法分析
Jul 15 #PHP
Yii控制器中filter过滤器用法分析
Jul 15 #PHP
Yii编程开发常见调用技巧集锦
Jul 15 #PHP
如何正确配置Nginx + PHP
Jul 15 #PHP
Yii净化器CHtmlPurifier用法示例(过滤不良代码)
Jul 15 #PHP
Yii列表定义与使用分页方法小结(3种方法)
Jul 15 #PHP
session 加入redis的实现代码
Jul 15 #PHP
You might like
世界收音机发展史
2021/03/01 无线电
php调用mysql存储过程
2007/02/14 PHP
用PHP控制用户的浏览器--ob*函数的使用说明
2007/03/16 PHP
php select,radio和checkbox默认选择的实现方法
2010/05/15 PHP
phplist及phpmailer(组合使用)通过gmail发送邮件的配置方法
2016/03/30 PHP
jquery form表单提交插件asp.net后台中文解码
2010/06/12 Javascript
javscript对象原型的一些看法
2010/09/19 Javascript
jQuery中绑定事件的命名空间详解
2011/04/05 Javascript
解决jquery submit()提交表单提示:f[s] is not a function
2013/01/23 Javascript
自定义右键属性覆盖浏览器默认右键行为实现代码
2013/02/02 Javascript
js实现的标题栏新消息闪烁提示效果
2014/06/06 Javascript
javascript动画算法实例分析
2015/07/31 Javascript
基于JS模仿windows文件按名称排序效果
2016/06/29 Javascript
使用do...while的方法输入一个月中所有的周日(实例代码)
2016/07/22 Javascript
浅谈基于Vue.js的移动组件库cube-ui
2017/12/20 Javascript
js 数组详细操作方法及解析合集
2018/06/01 Javascript
JavaScript使用递归和循环实现阶乘的实例代码
2018/08/28 Javascript
JQuery中queue方法用法示例
2019/01/31 jQuery
快速了解Node中的Stream流是什么
2019/02/13 Javascript
微信小程序实现购物页面左右联动
2019/02/15 Javascript
Python网络爬虫神器PyQuery的基本使用教程
2018/02/03 Python
Python将DataFrame的某一列作为index的方法
2018/04/08 Python
快速解决pandas.read_csv()乱码的问题
2018/06/15 Python
Python csv模块使用方法代码实例
2019/08/29 Python
windows 10 设定计划任务自动执行 python 脚本的方法
2019/09/11 Python
python实现网站微信登录的示例代码
2019/09/18 Python
PyCharm第一次安装及使用教程
2020/01/08 Python
django配置app中的静态文件步骤
2020/03/27 Python
电子商务专业在校生实习自我鉴定
2013/09/29 职场文书
怎样写演讲稿
2014/01/04 职场文书
家长学校实施方案
2014/03/15 职场文书
幼儿园区域活动总结
2014/05/08 职场文书
火箭队口号
2014/06/18 职场文书
未中标通知书
2015/04/17 职场文书
python设置 matplotlib 正确显示中文的四种方式
2021/05/10 Python
Win11开始菜单添加休眠选项
2022/04/19 数码科技