Skip to content

Instantly share code, notes, and snippets.

@enijar
Created July 11, 2016 16:52
Show Gist options
  • Save enijar/9e3dc28e258e5a3490463f361c73d0e3 to your computer and use it in GitHub Desktop.
Save enijar/9e3dc28e258e5a3490463f361c73d0e3 to your computer and use it in GitHub Desktop.
Safe Image Upload
<?php
namespace App\Soberistas\Assets;
use Intervention\Image\Constraint;
use Intervention\Image\ImageManager;
// TODO: We might want to remove this. It was added to deal with large images.
ini_set('memory_limit', -1);
class Image
{
private $allowedMimeTypes = [
'image/jpeg',
'image/png',
'image/gif',
];
private $maxSize = 5000000; // 5MB
private $maxPixelSize = 2000;
/**
* @param \Symfony\Component\HttpFoundation\File\UploadedFile|array|null $file
* @return array|bool
*/
public function save($file)
{
if (!in_array($file->getMimeType(), $this->allowedMimeTypes)) {
return [
'success' => false,
'message' => 'Invalid file type'
];
}
if ($file->getSize() > $this->maxSize) {
return [
'success' => false,
'message' => 'Invalid file size'
];
}
// Re-save the uploaded file to an image to prevent
// scripts from being uploaded that would otherwise
// be a security threat.
$manager = new ImageManager();
$image = $manager->make($file->getRealPath());
$image->save($file->getRealPath());
$image = $manager->make($file->getRealPath());
// Double check the mime-type is the correct one after re-saving.
if (!in_array($image->mime(), $this->allowedMimeTypes)) {
return [
'success' => false,
'message' => 'Invalid file type'
];
}
// Create a unique image hash.
$hash = bin2hex(openssl_random_pseudo_bytes(32)) . time();
// Limit the pixel size of the image.
if ($image->getWidth() > $this->maxPixelSize || $image->getHeight() > $this->maxPixelSize) {
$width = $image->getWidth() > $this->maxPixelSize ? $this->maxPixelSize : $image->getWidth();
$height = $image->getHeight() > $this->maxPixelSize ? $this->maxPixelSize : $image->getHeight();
$image->resize($width, $height, function (Constraint $constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// Save all image as jpeg.
$image->save(public_path("uploads/{$hash}.jpg"));
return [
'success' => true,
'name' => $file->getClientOriginalName(),
'size' => $file->getSize(),
'mime_type' => $image->mime(),
'public_path' => "uploads/{$hash}.jpg",
'hash' => $hash
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment