php copy()函数复制拷贝文件使用实例讲解

时间:2016-08-14
copy() 函数用于拷贝文件,如果成功则返回 TRUE,失败则返回 FALSE。本文章向大家介绍php copy()函数的基本语法和使用实例,需要的朋友可以参考一下。

php copy()函数介绍

copy — 复制拷贝文件

语法:

bool copy ( string $source , string $dest [, resource $context ] )

将文件从 source 复制拷贝到 dest。 如果要移动文件的话,请使用rename()函数。 

参数:

  1. source:源文件路径。 
  2. dest:目标路径。如果 dest 是一个 URL,则如果封装协议不支持覆盖已有的文件时拷贝操作会失败。 如果目标文件已存在,将会被覆盖。 
  3. context:A valid context resource created with stream_context_create(). 

返回值:

成功时返回 TRUE, 或者在失败时返回 FALSE。 

php copy()函数实例

使用copy()函数复制拷贝文件

<?php
   $source = "./test.txt";
   $destination = "./copy.txt";
                
   if(copy($source, $destination)) {
      echo "File copied successfully.", "\n";
   } else {
      echo "The specified file could not be copied. Please try again.", "\n";
   }
               
?>

例外一种方法实现复制拷贝文件(不使用copy()函数)

<?php 
function copyfiles($file1,$file2){ 
 $contentx =@file_get_contents($file1); 
  $openedfile = fopen($file2, "w"); 
  fwrite($openedfile, $contentx); 
  /* http://www.manongjc.com/article/1350.html */
  fclose($openedfile); 
   if ($contentx === FALSE) { 
   $status=false; 
   }else $status=true; 
   return $status; 
  } 
?>