2023-06-26 03:56:48 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace api\utils;
|
|
|
|
|
|
|
|
use Psr\Http\Message\UploadedFileInterface;
|
2023-07-12 03:29:56 +01:00
|
|
|
use RecursiveDirectoryIterator;
|
|
|
|
use RecursiveIteratorIterator;
|
2023-06-26 03:56:48 +01:00
|
|
|
|
|
|
|
class imgUtils
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Checks and uploads a file to the given directory
|
|
|
|
* @param string $targetDir - Directory to upload the file to
|
|
|
|
* @param UploadedFileInterface $img - File to upload
|
|
|
|
* @return string|array - String with error message or array with the location of the uploaded file
|
|
|
|
*/
|
|
|
|
public function uploadFile(string $targetDir, UploadedFileInterface $img): string|array
|
|
|
|
{
|
|
|
|
$targetFile = $targetDir . basename($img->getClientFilename());
|
|
|
|
$uploadOk = 1;
|
|
|
|
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
|
|
|
|
|
|
|
|
// Check if file already exists
|
|
|
|
if (file_exists($targetFile))
|
|
|
|
{
|
|
|
|
return "The file already exists";
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check file size
|
|
|
|
if ($img->getSize() > 2000000)
|
|
|
|
{
|
|
|
|
return "The file is too large, max 2MB";
|
|
|
|
}
|
|
|
|
|
|
|
|
// Allow certain file formats
|
|
|
|
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
|
|
|
|
{
|
|
|
|
return "Only JPG, JPEG, PNG & GIF files are allowed";
|
|
|
|
}
|
|
|
|
|
|
|
|
$img->moveTo($targetFile);
|
|
|
|
|
|
|
|
return array("imgLocation" => $targetFile);
|
|
|
|
}
|
2023-07-12 03:29:56 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Deletes a directory and all its contents
|
|
|
|
* @param string $path - Path to the directory to delete
|
|
|
|
*/
|
|
|
|
public function deleteDirectory(string $path): void
|
|
|
|
{
|
|
|
|
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path,
|
|
|
|
RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
|
|
|
|
|
|
|
foreach ($iterator as $file)
|
|
|
|
{
|
|
|
|
if ($file->isDir())
|
|
|
|
{
|
|
|
|
rmdir($file->getPathname());
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
unlink($file->getPathname());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
rmdir($path);
|
|
|
|
}
|
|
|
|
|
2023-06-26 03:56:48 +01:00
|
|
|
}
|