How to move files with PHP copy?

-1

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

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.";
   }
    
asked by anonymous 02.04.2016 / 19:07

2 answers

7

Moving files is rename , not copy :

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

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

As for "not wanting" the name in the destination, 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 were mine, of the name in both places and resolved).


Solution

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

Please note that I have not added protection to detect whether the destination path has the trailing slash or not. Provide the parameter without the slash (or adjust the function, probably using rtrim to get the final slash).


If you really want to use copy

Just use exactly the same function, changing the line of the return to

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

In this case, you need to adjust the function as you see fit to return and treat situations like the copy succeeded, but the deletion does not.

    
02.04.2016 / 23:08
1

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

I do not know if you want to set the filename 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.";
}

?>
    
02.04.2016 / 22:44