Based on the advice given by @Rodigorigotti, I developed a code to delete undesirable extension files. The extraction is done to a secure folder, so as not to give direct access to the folder to the user (thus avoiding a PHP Injection).
public function postAjaxUploadZip($id) {
$file = Input::file('zip');
$rules = [
'zip' => 'required|mimes:zip'
];
$messages = [
'mimes' => "Extensão de arquivo inválida"
];
$validation = Validator::make(Input::all(), $rules, $messages);
if ($validation->passes()) {
try{
$zip = $file->getRealPath();
$zipObject = new ZipArchive;
if (! $zipObject->open($zip)) {
throw new RunTimeException('Não foi possível abrir o arquivo enviado');
}
$path = base_path("secure/{$id}");
if (! File::isDirectory($path)) {
File::makeDirectory($path, 0755);
}
// Extrai para uma pasta segura, para o usuário não ter acesso a esses arquivos pelo pasta "public" do Laravel
$zipObject->extractTo($path);
// Itera com os arquivos do diretório onde houve a extração
$files = new FileSystemIterator($path);
foreach ($files as $file) {
$data = [
'file' => $file->getRealPath()
];
$rules = ['file' => 'mimes:jpg,png,bmp,jpeg'];
if (Validator::make($data, $rules)->fails()) {
$deletedFiles[] = $file->getFilename();
}
}
File::delete($filesToDelete);
} catch (Exception $e) {
return Response::json([
'error' => $e->getMessage(),
'directory' => $path,
]);
}
return Response::json([
'error' => false,
'deletedFiles' => $filesToDelete
]);
} else {
return Response::json(['error' => $validation->messages()]);
}
}
If anyone has a better idea, it’ll be a big help.
The less code the better!
Isn’t it easier to extract everything and enjoy only what is image? The rest you can delete throughout your routine.
– Rodrigo Rigotti
I thought the same thing, @Rodrigorigotti. While the answer is not enough, I will use the
FileSystemIterator
for that reason!– Wallace Maxters