How to move files with PHP copy?

Asked

Viewed 8,580 times

0

Using PHP copy, how can I copy the file to a particular folder without having to indicate the previous file name?

Example:

<?php
   // aqui eu indico o diretorio onde esta e o nome do arquivo
   $origem = 'pasta1/s.txt';

   // aqui eu indico a pasta de destino mas eu n quero colocar o nome aqui.
   // so a pasta e fazer a copia do arquivo. 
   $destino = 'teste/s.txt';

   if (copy($origem, $destino))
   {
      echo "Arquivo copiado com Sucesso.";
   }
   else
   {
      echo "Erro ao copiar arquivo.";
   }

2 answers

9


Move files is with rename, and not with copy:

bool rename ( string $oldname , string $newname [, resource $context ] )

Note that in Windows, the rename only moves between different disks from version 5.3.1

As for "not wanting" to put the name on the target, it seems to me an artificial requirement of your code, but if that’s what you want, just create a function for it (if the code was mine, I would simply put the name variable in both places and solved).


Solution

function moveSemPorONome( $origemComNome, $destinoSemNome ) {
   $partes = pathinfo( $origemComNome);
   $destinoComNome = $destinoSemNome . DIRECTORY_SEPARATOR . $partes['basename'];
   return rename( $origemComNome, $destinoComNome );
}

Note that I have not added protection to detect if the destination path is with the final bar or not. Provide the parameter without the slider (or add adjust the function, probably using rtrim to remove the final bar).


If you really want to use the copy

Just use exactly the same function, changing the Return line to

   return copy( $origemComNome, $destinoComNome ) && unlink( $origemComNome );

In this case, you need to adjust the function the way you think it is appropriate to return and treat situations like the copy being successful, but the deletion is not.

  • 1

    thanks for the tip

2

The PHP copy function requires the file name, both in source and destination.

I don’t know if what you want is to fix the file name in the code.

<?php
$pastaO = "pasta1/"; // pasta de origem
$pastaD = "teste/"; // pasta de destino
$arquivo = "s.txt"; // arquivo

if (copy($pastaO.$arquivo, $pastaD.$arquivo))
{
echo "Arquivo copiado com Sucesso.";
}
else
{
echo "Erro ao copiar arquivo.";
}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.