当前位置:首页 > PHP教程 > php文件操作 > 列表

PHP目录/文件拷贝/复制自定义函数分享

发布:smiling 来源: PHP粉丝网  添加日期:2016-08-25 13:59:48 浏览: 评论:0 

本文我们分享两个PHP复制目录或者文件的自定义函数dir_copy($src = '', $dst = ''),后面分享的函数可以复制文件夹及下面所有文件.

文件夹文件拷贝/复制函数如下:

  1. /** 
  2.  * 文件夹文件拷贝 
  3.  * 
  4.  * @param string $src 来源文件夹 
  5.  * @param string $dst 目的地文件夹 
  6.  * @return bool 
  7.  */ 
  8. function dir_copy($src = '', $dst = '') 
  9. { 
  10.     if (emptyempty($src) || emptyempty($dst)) 
  11.     { 
  12.         return false; 
  13.     } 
  14.     $dir = opendir($src); 
  15.     dir_mkdir($dst); 
  16.     while (false !== ($file = readdir($dir))) 
  17.     { 
  18.         if (($file != '.') && ($file != '..')) 
  19.         { 
  20.             if (is_dir($src . '/' . $file)) 
  21.             { 
  22.                 dir_copy($src . '/' . $file, $dst . '/' . $file); 
  23.             } 
  24.             else 
  25.             { 
  26.                 copy($src . '/' . $file, $dst . '/' . $file); 
  27.             } 
  28.         } 
  29.     } 
  30.     closedir($dir); 
  31.     return true; 
  32. } 
  33. /** 
  34.  * 创建文件夹 
  35.  * 
  36.  * @param string $path 文件夹路径 
  37.  * @param int $mode 访问权限 
  38.  * @param bool $recursive 是否递归创建 
  39.  * @return bool 
  40.  */ 
  41. function dir_mkdir($path = '', $mode = 0777, $recursive = true) 
  42. { 
  43.     clearstatcache(); 
  44.     if (!is_dir($path)) 
  45.     { 
  46.         mkdir($path, $mode, $recursive); 
  47.         return chmod($path, $mode); 
  48.     } //phpfensi.com 
  49.     return true; 
  50. } 

PHP复制文件夹及下面所有文件,参考如下:

  1. function xCopy($source, $destination, $child){ 
  2.   //用法: 
  3.   // xCopy("feiy","feiy2",1):拷贝feiy下的文件到 feiy2,包括子目录 
  4.   // xCopy("feiy","feiy2",0):拷贝feiy下的文件到 feiy2,不包括子目录 
  5.   //参数说明: 
  6.   // $source:源目录名 
  7.   // $destination:目的目录名 
  8.   // $child:复制时,是不是包含的子目录 
  9.   if(!is_dir($source)){ 
  10.     echo("Error:the $source is not a direction!"); 
  11.     return 0; 
  12.   } 
  13.   if(!is_dir($destination)){ 
  14.     mkdir($destination,0777); 
  15.   } 
  16.   $handle=dir($source); 
  17.   while($entry=$handle->read()) { 
  18.     if(($entry!=".")&&($entry!="..")){ 
  19.       if(is_dir($source."/".$entry)){ 
  20.         if($child) 
  21.         xCopy($source."/".$entry,$destination."/".$entry,$child); 
  22.       } 
  23.       else{ 
  24.         copy($source."/".$entry,$destination."/".$entry); 
  25.       } 
  26.     } 
  27.   } 
  28.   return 1; 
  29. } 

Tags: PHP目录 PHP文件拷贝

分享到: