Created
March 13, 2016 19:52
-
-
Save davidmz/2f3056ee86af75cf2f71 to your computer and use it in GitHub Desktop.
Пример загрузки файла-картинки на PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$strTargetDir = "user_images/"; | |
$fileUploadField = "file_name"; | |
$max_image_width = 600; | |
$max_image_height = 600; | |
$max_image_size = 1 << 20; // 1 MiB | |
$error_msg = ""; | |
// .... | |
if (!isset($_FILES[$fileUploadField])) { | |
// в форме нет нужного поля | |
throw new Exception('Invalid form data'); | |
} | |
$uploaded = $_FILES[$fileUploadField]; | |
if ($uploaded['error'] != 0 /*UPLOAD_ERR_OK*/) { | |
throw new Exception("Upload error ({$uploaded['error']})"); | |
} | |
if ($uploaded['size'] > $max_image_size) { | |
throw new Exception('File too big!'); | |
} | |
// временный файл для перемещения загруженного | |
$tmpFileName = $strTargetDir.uniqid("upl"); | |
if (!move_uploaded_file($uploaded["tmp_name"], $tmpFileName)) { | |
throw new Exception('Error moving uploaded file'); | |
} | |
// Определяем формат и размеры картинки. Формат надо определять | |
// именно по содержимому файла, а не по расширению т. к. расширение | |
// может быть любым. | |
$imgInfo = getimagesize($tmpFileName); | |
if (!$imgInfo) { | |
throw new Exception('File is not an image'); | |
} | |
list($width, $height, $type) = $imgInfo; | |
$ext = ""; | |
if ($type == IMAGETYPE_JPEG) { | |
$ext = "jpg"; | |
} elseif ($type == IMAGETYPE_GIF) { | |
$ext = "gif"; | |
} elseif ($type == IMAGETYPE_PNG) { | |
$ext = "png"; | |
} else { | |
throw new Exception('Wrong image type: only GIF, PNG, and JPG (JPEG) files'); | |
} | |
if ($width > $max_image_width or $height > $max_image_height) { | |
throw new Exception("Image dimension(s) exceed(s) {$max_image_width}x{$max_image_height}"); | |
} | |
// Все проверки закончены, пора переименовывать файл. Я бы не советовал | |
// брать имя из $uploaded['name'] — там может быть всё что угодно, в том числе слэши, | |
// всякие запрещённые символы, и файл может вовсе не переименоваться или же | |
// потом будут проблемы с его удалением. Лучше сделать синтетическое имя. | |
// Тут имя делается из хэша содержимого файла. Как побочный эффект, два одинаковых файла | |
// будут иметь одно и то же имя, т. е. не сохраняться два раза. | |
$tgtFileName = $strTargetDir.md5_file($tmpFileName).".".$ext; | |
if (file_exists($tgtFileName)) { | |
// уже есть такой файл | |
unlink($tmpFileName); | |
} elseif (!rename($tmpFileName, $tgtFileName)) { | |
throw new Exception('Error moving file'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment