Copy and rename files php

Copy and rename multiple files with PHP

Solution 1: You can use copy() to copy a file with PHP: If this does not work, you might have a problem with your code, access rights, or something else. Solution 2: you can use copy function in php Solution 3: you can use copy function Docs link: http://www.php.net/manual/en/function.copy.php Solution: use this function Solution:

Copy and rename multiple files with PHP

One approach (untested) that you can take is creating a class to duplicate a directory. You mentioned you would need to get the name of the files in a directory and this approach will handle it for you.

It will iterate over an array of names (whatever you pass to it), and copy/rename all of the files inside a directory of your choice. You might want to add some checks in the copy() method ( file_exists , etc) but this will definitely get you going and is flexible.

// Instantiate, passing the array of names and the directory you want copied $c = new CopyDirectory(['London', 'New-York', 'Seattle'], 'location/of/your/directory/'); // Call copy() to copy the directory $c->copy(); /** * CopyDirectory will iterate over all the files in a given directory * copy them, and rename the file by appending a given name */ class CopyDirectory < private $imageNames; // array private $directory; // string /** * Constructor sets the imageNames and the directory to duplicate * @param array * @param string */ public function __construct($imageNames, $directory) < $this->imageNames = $imageNames; $this->directory = $directory; > /** * Method to copy all files within a directory */ public function copy() < // Iterate over your imageNames foreach ($this->imageNames as $name) < // Locate all the files in a directory (array_slice is removing the trailing ..) foreach (array_slice(scandir($this->directory),2) as $file) < // Generates array of path information $pathInfo = pathinfo($this->directory . $file); // Copy the file, renaming with $name appended copy($this->directory . $file, $this->directory . $pathInfo['filename'] . '-' . $name .'.'. $pathInfo['extension']); > > > > 

You could use a regular expression to build the new filenames, like this:

$fromFolder = 'Images/folder/'; $fromFile = 'service.jpg'; $toFolder = 'Images/folder/'; $imgnames = array('London', 'New-York','Seattle'); foreach ($imgnames as $imgname) < $newFile = preg_replace("/(\.[^\.]+)$/", "-" . $imgname . "$1", $fromFile); echo "Copying $fromFile to $newFile"; copy($fromFolder . $fromFile, $toFolder . $newFile); >

The above will output the following while copying the files:

Copying service.jpg to service-London.jpg Copying service.jpg to service-New-York.jpg Copying service.jpg to service-Seattle.jpg 

In the above code, set the $fromFolder and $toFolder to your folders, they can be the same folder, if so needed.

Php copy a variable Code Example,

Copy Files to another folder PHP

You can use copy() to copy a file with PHP:

if (!copy('PATTERN/index.php', $Username.'/index.php'))

If this does not work, you might have a problem with your code, access rights, or something else. Without your code and the exact description of the error message (if any) it will be hard to help you.

you can use copy function in php

copy('PATTERN/index.php', 'USERNAME/index.php'); 

you can use copy function

 // Will copy abc/a.php to xyz/x.php copy('abc/a.php', 'xyz/x.php'); 

Docs link: http://www.php.net/manual/en/function.copy.php

Читайте также:  Css borders on table row

Copy files from one server to another using php,

How can I copy a folder to another folder with Laravel?

function recursive_files_copy($source_dir, $destination_dir) < // Open the source folder / directory $dir = opendir($source_dir); // Create a destination folder / directory if not exist if (!is_dir($destination_dir))< mkdir($destination_dir); >// Loop through the files in source directory while($file = readdir($dir)) < // Skip . and .. if(($file != '.') && ($file != '..')) < // Check if it's folder / directory or file if(is_dir($source_dir.'/'.$file)) < // Recursively calling this function for sub directory recursive_files_copy($source_dir.'/'.$file, $destination_dir.'/'.$file); >else < // Copying the files copy($source_dir.'/'.$file, $destination_dir.'/'.$file); >> > closedir($dir); > 

«Copy» a php-file and include the POST-variable, Based on a form input, it creates a folder with the input name, eg. JOHN. (called $dir) · It then creates a MySQL database table with the name

Copy a file and create a directory if it doesn’t exist in PHP [duplicate]

function mycopy($s1, $s2) < $path = pathinfo($s2); if (!file_exists($path['dirname'])) < mkdir($path['dirname'], 0777, true); >if (!copy($s1, $s2)) < echo "copy failed \n"; >> 

Copy file into new directory (PHP), You’re trying to write the file twice, first time you try to copy it and then you try to put the contents but you pass a bool as a file content.

Источник

copy

If you wish to move a file, use the rename() function.

Parameters

The destination path. If to is a URL, the copy operation may fail if the wrapper does not support overwriting of existing files.

If the destination file already exists, it will be overwritten.

A valid context resource created with stream_context_create() .

Return Values

Returns true on success or false on failure.

Examples

Example #1 copy() example

$file = ‘example.txt’ ;
$newfile = ‘example.txt.bak’ ;

if (! copy ( $file , $newfile )) echo «failed to copy $file . \n» ;
>
?>

See Also

  • move_uploaded_file() — Moves an uploaded file to a new location
  • rename() — Renames a file or directory
  • The section of the manual about handling file uploads

User Contributed Notes 24 notes

Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the ‘destination’ needs to contain the actual file name ! — NOT just the path to the folder you wish to copy into.
DOH !
hope this saves somebody hours of fruitless debugging

It take me a long time to find out what the problem is when i’ve got an error on copy(). It DOESN’T create any directories. It only copies to existing path. So create directories before. Hope i’ll help,

On Windows, php-7.4.19-Win32-vc15-x64 — copy() corrupted a 6GB zip file. Our only recourse was to write:

function file_win_copy( $src, $dst ) shell_exec( ‘COPY «‘.$src.'» «‘.$dst.'»‘);
return file_exists($dest);
>

Don’t forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g.

if(!@ copy ( ‘http://someserver.com/somefile.zip’ , ‘./somefile.zip’ ))
$errors = error_get_last ();
echo «COPY ERROR: » . $errors [ ‘type’ ];
echo «
\n» . $errors [ ‘message’ ];
> else echo «File copied from remote!» ;
>
?>

Читайте также:  METANIT.COM

Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.

I am using these for managing folders and zip archives for my website plugins.

// removes files and non-empty directories
function rrmdir ( $dir ) if ( is_dir ( $dir )) $files = scandir ( $dir );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rrmdir ( » $dir / $file » );
rmdir ( $dir );
>
else if ( file_exists ( $dir )) unlink ( $dir );
>

// copies files and non-empty directories
function rcopy ( $src , $dst ) if ( file_exists ( $dst )) rrmdir ( $dst );
if ( is_dir ( $src )) mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rcopy ( » $src / $file » , » $dst / $file » );
>
else if ( file_exists ( $src )) copy ( $src , $dst );
>
?>

Cheers!

A nice simple trick if you need to make sure the folder exists first:

$srcfile = ‘C:\File\Whatever\Path\Joe.txt’ ;
$dstfile = ‘G:\Shared\Reports\Joe.txt’ ;
mkdir ( dirname ( $dstfile ), 0777 , true );
copy ( $srcfile , $dstfile );

Below a code snippet for downloading a file from a web server to a local file.

It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.

It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual «not found» page, instead of a proper 404 return code.

// $fURI: URL to a file located on a web server
// $target_file: Path to a local file

if ( file_exists ( $target_file ) ) $ifmodhdr = ‘If-Modified-Since: ‘ . date ( «r» , filemtime ( $target_file ) ). «\r\n» ;
>
else $ifmodhdr = » ;
>

// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
‘http’ =>array(
‘method’ => ‘GET’ ,
‘protocol_version’ => 1.1 ,
‘follow_location’ => 1 ,
‘header’ => «User-Agent: Anamera-Feed/1.0\r\n» .
«Referer: $source \r\n» .
$ifmodhdr
)
);
$rc = copy ( $fURI , $target_file , stream_context_create ( $arrRequestHeaders ) );

// HTTP request completed, preserve system error, if any
if( $rc ) if ( fclose ( $rc ) ) unset( $err );
>
else $err = error_get_last ();
>
>
else $err = error_get_last ();
>

// Parse HTTP Response Headers for HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) for ( $i = sizeof ( $http_response_header ) — 1 ; $i >= 0 ; $i — ) if ( preg_match ( ‘@^http/\S+ (\S) (.+)$@i’ , $http_response_header [ $i ], $http_status ) > 0 ) // HTTP Status header means we have reached beginning of response headers for last request
break;
>
elseif ( preg_match ( ‘@^(\S+):\s*(.+)\s*$@’ , $http_response_header [ $i ], $arrHeader ) > 0 ) switch ( $arrHeader [ 1 ] ) case ‘Last-Modified’ :
if ( !isset( $http_content_modtime ) ) $http_content_modtime = strtotime ( $arrHeader [ 2 ] );
>
break;
case ‘Content-Type’ :
if ( !isset( $http_content_image_type ) ) if ( preg_match ( ‘@^image/(\w+)@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) if ( in_array ( strtolower ( $arrTokens [ 1 ]), $arrValidTypes )) $http_content_image_type = $arrTokens [ 1 ];
break;
>
>
throw new Exception ( «Error accessing file $fURI ; invalid content type: $arrHeader [ 2 ] » , 2 );
>
break;
case ‘Content-Disposition’ :
if ( !isset( $http_content_filename ) && preg_match ( ‘@filename\\s*=\\s*(?|»([^»]+)»|([\\S]+));?@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) $http_content_filename = basename ( $arrTokens [ 1 ]);
>
break;
>
>
>
>

Читайте также:  Php curl get запрос headers

if ( $http_status ) // Make sure we have good HTTP Status
switch ( $http_status [ 1 ] ) case ‘200’ :
// SUCCESS: HTTP Status is «200 OK»
break;
case ‘304’ :
throw new Exception ( «Remote file not newer: $fURI » , $http_status [ 1 ] );
break;
case ‘404’ :
throw new Exception ( «Remote file not found: $fURI » , $http_status [ 1 ] );
break;
default:
throw new Exception ( «HTTP Error, $http_status [ 2 ] , accessing $fURI » , $http_status [ 1 ] );
break;
>
>
elseif ( $err ) // Protocol / Communication error
throw new Exception ( $err [ ‘message’ ] /*.»; Remote file: $fURI»*/ , $err [ ‘type’ ] );
>
else // No HTTP status and no error
throw new customException ( «Unknown HTTP response accessing $fURI : $http_response_header [ 0 ] » , — 1 );
>
?>

Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.

Источник

Копирование, переименование и перемещение файлов в PHP

В статье продолжается описание способов работы с файлами в PHP и применение различных функций для управления ими. Информацию по созданию и записи файлов можно найти в статье «Создание, открытие, чтение, запись, удаление и проверка наличия файла в PHP». Здесь рассматривается работа с уже существующими файлами.

Копирование файла

Для копирования файла применяется функция copy. В ней должны быть заданы директория к исходному файлу и путь к новому создаваемому файлу. Путь можно задавать абсолютным адресом, то есть с указанием всех каталогов от корня. Можно так же задавать относительный путь.

Если файл скопирован, функция вернет значение True. Если копирование не выполнено, то будет возвращено значение False.

if (copy("myfile.txt", "newfile.txt"))
echo "Файл скопирован";
else
echo "Файл не был скопирован";

Если файл с заданным именем в директории уже есть, старый файл будет заменен новым с тем же именем. Поэтому, при копировании, стоит проверять, не существует ли файл в новой директории. Такую проверку выполняет функция file_exists.

$new_filename = "newfile.txt";

if (file_exists($new_filename))
echo "Такой файл уже существует";
else
if (copy("myfile.txt", "newfile.txt"))
echo "Файл скопирован";
else
echo "Файл не был скопирован";

Переименование и перемещение файла

Переименование и перемещение файла можно выполнить одной функцией rename.

Для переименования в параметрах функции указывается имя исходного файла, а вторым параметром, задается новое имя.

rename("myfile.txt", "newname.txt");

При удачном выполнении функции, возвращается результат True, в противном случае False.

if (rename("myfile.txt", "newname.txt"))
echo "Файл переименован";
else
echo "Файл не был переименован";

Для перемещения файла, задается новый путь к файлу:

rename("myfile.txt", "newfolder/myfile.txt");

Понятно, что при необходимости, и перемещение и переименование файла можно выполнить одновременно. Для этого достаточно в новом пути задать новый каталог и новое имя файла.

rename("myfile.txt", "newfolder/newfile.txt");

Источник

Оцените статью