Delete residual Word file from my project

0

You see, I have the following code:

public function imprimirWord(Juego $j){
    $phpWord=new \PhpOffice\PhpWord\PhpWord();
    $phpWord->getSettings()->setThemeFontLang(new Language(Language::ES_ES));
    $section=$phpWord->addSection();

    $text=$section->addText('Juego Nº '.$j->numero.': '.$j->nombre,array('name'=>'Arial','size' => 15,'bold' => true));
    $section->addImage($j->ruta(), array('width'=>400, 'height'=>300, 'align'=>'center'));
    $text=$section->addText("-Materiales requeridos: ".$j->materiales);
    $text=$section->addText("-Agrupación: ".$j->organizacion);
    $text=$section->addText("-Cómo se organiza el juego: ".$j->agrupacion->nombre);
    $text=$section->addText("-Desarrollo del juego: ".$j->desarrollo);
    if($j->observaciones!='*')
        $text=$section->addText("-Reglas y observaciones: ".$j->observaciones);
    if($j->variantes!='*')
        $text=$section->addText("-Variantes del juego: ".$j->variantes);
    $contenidos=$j->enlaces;
    $valor=count($contenidos);
    if($valor){
        $texto="";
        foreach($contenidos as $contenido){
            $texto.=" ".$contenido->contenido->nombre;
            $valor--;
            if($valor>1)
                $texto.=",";
            else if($valor==1)
                $texto.=" y";
            else
                $texto.=".";
        }
        $text=$section->addText("-Contenidos del juego:".$texto);
    }

    $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $deciso='Juego Nº '.$j->numero.' - '.$j->nombre.'.docx';
    $objWriter->save($deciso);
    return response()->download(public_path($deciso));
}

This allows me to create a Word file, but there is a problem: It also creates a copy within my project. To fix it, I have this code: unlink($deciso); , which is responsible for removing the word file. And here comes my problem, that when I need to use return to create the fíchero, if I put this code after the creation of the document, it will not be executed. I need the user to receive their document without needing a return, so that after it is generated I can delete the document with unlink . How do I achieve it?

Edit: Something that I have been suggested is to save the file in the / tmp folder, since it will "restart" over time. When I create the file with save, the project is saved in public_html. How do I save it in the other folder?

    
asked by Miguel Alparez 15.09.2018 в 15:52
source

2 answers

0

I have already come up with a way to solve this. From the outset, I created the following in Juego.php:

public function ficheto(){
    return 'descargas/Juego Nº '.$this->numero.' - '.$this->nombre.'.docx';
}

The story is that to begin with I have created a folder "downloads", where from now on I will store Word files. The next step is to make this radical change:

public function imprimirWord(Juego $j){
    $deciso=$j->ficheto();
    if(!file_exists($deciso)){
        $phpWord=new \PhpOffice\PhpWord\PhpWord();
        $phpWord->getSettings()->setThemeFontLang(new Language(Language::ES_ES));
        $section=$phpWord->addSection();

        $text=$section->addText('Juego Nº '.$j->numero.': '.$j->nombre, array('name'=>'Arial','size' => 15,'bold' => true));
        $section->addImage($j->ruta(), array('width'=>400, 'height'=>300, 'align'=>'center'));
        $general=array('bold'=>true);

        $text=$section->addText("-Materiales requeridos: ", $general);
        $text=$section->addText($j->materiales);

        $text=$section->addText("-Agrupación: ", $general);
        $text=$section->addText($j->organizacion);

        $text=$section->addText("-Cómo se organiza el juego: ", $general);
        $text=$section->addText($j->agrupacion->nombre);

        $text=$section->addText("-Desarrollo del juego: ", $general);
        $text=$section->addText($j->desarrollo);

        if($j->observaciones!='*'){
            $text=$section->addText("-Reglas y observaciones: ", $general);
            $text=$section->addText($j->observaciones);
        }

        if($j->variantes!='*'){
            $text=$section->addText("-Variantes del juego: ", $general);
            $text=$section->addText($j->variantes);
        }

        $contenidos=$j->enlaces;
        $valor=count($contenidos);
        if($valor){
            $texto="";
            foreach($contenidos as $contenido){
                $texto.=" ".$contenido->contenido->nombre;
                $valor--;
                if($valor>1)
                    $texto.=",";
                else if($valor==1)
                    $texto.=" y";
                else
                    $texto.=".";
            }
            $text=$section->addText("-Contenidos del juego:", $general);
            $text=$section->addText($texto);
        }

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($deciso);
    }
    return response()->download(public_path($deciso));
}

This will cause that in case that the file has already been created, it is downloaded directly so as not to have to recreate it again. This is more efficient for the user to give it the possibility that it takes less time to download, but it gives me a series of problems.

There are 2 that I discovered:

The first is that every time you modify or delete the game, it would be advisable to delete the file, since now the information in that file will be obsolete.

The second is that from now on I am obliged that there can not be 2 games that are called the same, since that could cause the Word of another game to be downloaded by mistake. This last will force me to make changes in my database.

Does anyone think of other complications that you need to consider?

    
answered by 18.09.2018 / 12:39
source
1

You can tell him to delete the file after downloading with deleteFileAfterSend(true)

return response()
   ->download($pathToFile, $name, $headers)
   ->deleteFileAfterSend(true);

$pathToFile is the path and name of the temporary file.

$name is the file name with which it will be saved on the client machine.

$headers are additional headers that you want to send next to the file.

An example of headers for word document:

$headers = array(
   'Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document;'
);

To create a temporary file with a unique name, you can use a md5 of the name microtime, something like this:

$tempDoc = md5($deciso . microtime());

And then when you send it you pass the correct name with the headers for word2007

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($tempDoc);

$headers = array(
   'Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document;'
);

return response()
  ->download($tempDoc, $deciso, $headers)
  ->deleteFileAfterSend(true);
    
answered by 18.09.2018 в 14:59