I have a folder that contains 3 subfolders and .txt files named like this :
I would like :
I've done this function, but it's not working... Where's my mistake?
<?php
function deplacementFile( $path ) {
$dir = './test/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".","..","FR", "ES", "PT")))
{
$file = $dir.$file;
$filename = basename( $file );
//read the entire string
$str = file_get_contents( $file );
if ( strpos( $filename, 'A500_' ) === 0 ) {
$dossierDestination1 = './test/FR/';
if(!copy($dir, $dossierDestination1)) {
echo "error copy";
} else {
if(!unlink($dir)) {
echo "error unlink";
}
}
}
else if ( strpos( $filename, 'A700_' ) === 0 ) {
$dossierDestination2 = './test/ES/';
if(!copy($dir, $dossierDestination2)) {
echo "error copy";
} else {
if(!unlink($dir)) {
echo "error unlink";
}
}
}
else if ( strpos( $filename, 'A900_' ) === 0 ) {
$dossierDestination3 = './test/PT/';
if(!copy($dir, $dossierDestination3)) {
echo "error copy";
} else {
if(!unlink($dir)) {
echo "error unlink";
}
}
}
else {
return false;
}
}
}
}
deplacementFile( './test/' );
echo "Successfully completed!";
?>
Here's a upgraded version of your script:
function deplacementFile( $path ) {
$dir = './test/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".","..","FR", "ES", "PT")))
{
// $file - is PATH to copied file
$file = $dir.$file;
// $filename - is the name of file being copied
$filename = basename( $file );
$paths = [
'A500_' => './test/FR/',
'A700_' => './test/ES/',
'A900_' => './test/PT/',
];
foreach ($paths as $key => $dest) {
if (strpos( $filename, $key ) === 0) {
// copy from PATH to new path which is `dest and filename`
if(!copy($file, $dest . $filename)) {
echo "error copy";
} else {
if(!unlink($file)) {
echo "error unlink";
}
}
break;
}
}
}
}
}
Also, consider rename
which moves file, the arguments are the same, but you don't need unlink
.