I wrote this method to upload a floor plan image:
function upload_image($path, $file) {
$errors = [];
$ext = pathinfo($file["name"])['extension'];
//randomly generate filename to avoid conflicts
$filename = uniqid().'.'.$ext;
if ($file["size"] > 2000000) {
$errors[] = "The image cannot be greater than 2MB";
}
if (!in_array($ext, ["jpg", "jpeg", "png"])) {
$errors[] = "The image can only be of .jpg, .jpeg or .png format";
}
if (empty($errors)) {
move_uploaded_file($file["tmp_name"], $path.$filename);
}
return array(
"name" => $filename,
"errors" => $errors
);
}
Implementation:
if (isset($_POST['create'])) {
$image = upload_image(IMG_PATH."/floorplans/", $_FILES['floorplan']);
$floorplan = new FloorPlan($_POST['floorplan']);
if (empty($image['errors'])) {
$floorplan->image = $image['name'];
} else {
foreach ($image['errors'] as $error) {
$floorplan->errors[] = $error;
}
}
}
I'm very happy with it and everything seems to work fine, but I am just wondering if there is a better/more efficient way to do this.