0

I am trying to remove a file from folder using remove function of the filesystem component in Symfony 4.

Here is my code in the controller:

//Get old logo
$oldlogo = $employer->getLogo();
//If there is a old logo we need to detele it
     if($oldlogo){
       $filesystem = new Filesystem();
       $path=$this->getTargetDirectory().'/public/uploads/logos/'.$oldlogo;
       $filesystem->remove($path);
 }

private $targetDirectory;

public function __construct($targetDirectory)
    {
        $this->targetDirectory = $targetDirectory;
    }

public function getTargetDirectory()
    {
        return $this->targetDirectory;
    }

Service.yalm:

parameters:
    logos_directory: '%kernel.project_dir%/public/uploads/logos'

App\Controller\EmployerController:
        arguments:
            $targetDirectory: '%logos_directory%'

I have no error message but the file not deleted from the folder.

Alex G
  • 31
  • 1
  • 10
  • Have a look at https://stackoverflow.com/questions/52850493/symfony-4-get-the-root-path-of-the-project-from-a-custom-class-not-a-controlle about how to inject your kernel properly – Nico Haase May 01 '20 at 19:02
  • Done. I updated the code in my message. No error message anymore but the file is not deleted from the folder. – Alex G May 01 '20 at 20:27

1 Answers1

0

I using this solution:

in my services.yaml I add:

public_directory: '%kernel.project_dir%/public'

and in my controller I use

$filesystem = new Filesystem();
$path=$this->getParameter("public_directory").'/uploads/logos/'.$oldlogo;
$filesystem->remove($path);
giovybus
  • 349
  • 1
  • 3
  • 10
  • I edited my message with my new code. (I also tried your solution). With my new code or your proposed solution I have no error message but the file is not deleted from the folder. – Alex G May 01 '20 at 20:26
  • try to print the $path and check if there is any problem – giovybus May 01 '20 at 20:37
  • When I print $path, I constat that there is a prefix on the filename. – Alex G May 01 '20 at 20:51
  • No in my project that code work, try to read the log if there are any suggest – giovybus May 01 '20 at 20:55
  • When I print $path, I constat that there is a prefix 'logos' on the filename. I print: .../public/uploads/logoslogocopie-5eac89d9110f8.png, name of the file in the folder is logocopie-5eac89d9110f8.png – Alex G May 01 '20 at 20:57
  • I was just a missing /... Thank you – Alex G May 01 '20 at 21:04