Skip to content

Instantly share code, notes, and snippets.

@ephod
Created December 24, 2018 13:12
Show Gist options
  • Save ephod/4cbd3bba970a66f96279b538c3e6ad3b to your computer and use it in GitHub Desktop.
Save ephod/4cbd3bba970a66f96279b538c3e6ad3b to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
if (
!isset($_FILES['files']) &&
!isset($_FILES['files']['tmp_name']) &&
!is_iterable($_FILES['files']['tmp_name'])
) {
echo "No files exist.";
//Exit execution
}
$file = new stdClass();
$imageExtensions = ["jpeg", "jpg", "png"];
$invalidTypes = implode(', ', $imageExtensions);
$twoMB = 2 * 1024 * 1024;
foreach (array_keys($_FILES['files']['tmp_name']) as $img) {
$file->name = $_FILES['files']['name'][$img] ?? '';
$size = $_FILES['files']['size'][$img] ?? 0;
$file->size = is_numeric($size) ? (int) $size : 0;
$file->tmpName = $_FILES['files']['tmp_name'][$img] ?? '';
$file->type = $_FILES['files']['type'][$img] ?? '';
$fileParts = explode('.', $file->name);
$file->extension = mb_strtolower(end($fileParts));
if (!in_array($file->extension, $imageExtensions, true)) {
//Check For Extension
echo "{$file->name} is an invalid image type<br/>";
echo "Please use one of these valid types: {$invalidTypes}<br/>";
continue;
}
if ($file->size > $twoMB) {
//Error For Large File Size.
echo "{$file->name} is too large to upload<br/>";
echo "Please upload a file under two MB<br/>";
continue;
}
//Upload Images to folder named 'gallery'
move_uploaded_file($file->tmpName, "gallery/{$file->name}");
echo "Successfully uploaded: {$file->name}<br/>";
//Do some SQL part here if you want.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment