Skip to content

Instantly share code, notes, and snippets.

@time-wcrp
Last active August 28, 2016 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save time-wcrp/cc90629324d16bbab35a325e582846af to your computer and use it in GitHub Desktop.
Save time-wcrp/cc90629324d16bbab35a325e582846af to your computer and use it in GitHub Desktop.
<?php
/**
* Version: 3
* Reference: https://devreply.com/questions/show/14
* Date: 2016-08-28
*/
/**
* @return bool
*/
function isPost()
{
return $_SERVER['REQUEST_METHOD'] === 'POST';
}
/**
* @param $file_data
* @return bool
*/
function isUpload($file_data)
{
return file_exists($file_data['tmp_name']) and is_uploaded_file($file_data['tmp_name']);
}
/**
* @param $file_data
* @return array
*/
function uploadFile($file_data)
{
$data = [
'status' => false,
'message' => '',
'image' => [],
];
$config = [
'type_whitelist' => [IMAGETYPE_JPEG],
'max_size' => 1 * 1000000,
'ext_list' => [
2 => 'jpg',
],
'path' => 'images/'
];
if (isset($file_data['error']) and $file_data['error'] === 0) {
if (isset($file_data['size']) and $file_data['size'] > 0 and $file_data['size'] < $config['max_size']) {
if (isset($file_data['tmp_name']) and in_array(exif_imagetype($file_data['tmp_name']), $config['type_whitelist'])) {
$data['image']['mimetype'] = $file_data['type'];
$data['image']['extension'] = $config['ext_list'][exif_imagetype($file_data['tmp_name'])];
$data['image']['basename'] = md5(file_get_contents($file_data['tmp_name']));
$data['image']['filename'] = $data['image']['basename'] . '.' . $data['image']['extension'];
$data['image']['size'] = $file_data['size'];
$data['image']['blob'] = file_get_contents($file_data['tmp_name']);
list($data['image']['width'], $data['image']['height']) = getimagesize($file_data['tmp_name']);
if (!is_file($config['path'] . $data['image']['filename'])) {
if (move_uploaded_file($file_data['tmp_name'], $config['path'] . $data['image']['filename'])) {
$data['status'] = true;
} else {
$data['message'] = 'เกิดปัญหาการย้ายไฟล์';
}
} else {
$data['status'] = true;
}
} else {
$data['message'] = 'รูปภาพไม่ใช่ชนิด JPEG';
}
} else {
$data['message'] = 'ขนาดไฟล์ต้องไม่มากกว่า 1MB';
}
} else {
$data['message'] = 'มีปัญหาระหว่างอัพโหลดรูปภาพ';
}
return $data;
}
$file_upload = (isset($_FILES['images'])) ? $_FILES['images'] : [];
if (isPost() and isUpload($file_upload)) {
$result = uploadFile($file_upload);
if ($result['status']) {
header('Content-Type: ' . $result['image']['mimetype']);
echo $result['image']['blob'];
} else {
echo $result['message'];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment