Miva Basket File Upload
<?php
header('Content-Type: application/json; charset=utf-8');
$STORE_CODE = 'ABC';
$BASKET_COOKIE_NAME = "mm5-$STORE_CODE-basket-id";
$UPLOAD_FOLDER = '../uploads/baskets';
$DS = DIRECTORY_SEPARATOR;
try
{
$basket_id = (int) $_REQUEST['basketID'];
$basket_cookie = $_COOKIE[ $BASKET_COOKIE_NAME ];
// Validate Session & Basket ID Cookie Value
if( !isValidMD5($basket_cookie) )
{
throw new RuntimeException('Error: Invalid session.');
}
// Validate Session & Basket ID Cookie Value
if( !$basket_id > 0 )
{
throw new RuntimeException('Error: Invalid Basket ID.');
}
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if ( !isset($_FILES['file']['error']) || is_array($_FILES['file']['error']) ) {
throw new RuntimeException('Error: Invalid parameters.');
}
// Check $_FILES['file']['error'] value.
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('Error: No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Error: Exceeded filesize limit.');
default:
throw new RuntimeException('Error: Unknown errors.');
}
// You should also check filesize here.
define('KB', 1024);
define('MB', 1048576);
define('GB', 1073741824);
define('TB', 1099511627776);
if ($_FILES['file']['size'] > 70*MB) {
throw new RuntimeException('Error: Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['file']['mime'] VALUE
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['file']['tmp_name']),
array(
'ai' => 'application/illustrator',
'bmp' => 'image/bmp',
'eps' => 'application/postscript',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'pdf' => 'application/pdf',
'png' => 'image/png',
'tiff' => 'image/tiff'
),
true
)) {
throw new RuntimeException('Error: Invalid file format.');
}
// You should name it uniquely too.
// DO NOT USE $_FILES['file']['name'] WITHOUT ANY VALIDATION !!
$slugified_file_name = slugify($_FILES['file']['tmp_name']).'.'.$ext;
$destinate_file_path = $UPLOAD_FOLDER.$ds.$basket_id.$ds.$slugified_file_name;
if (move_uploaded_file($_FILES['file']['tmp_name'], $destinate_file_path) ) {
$result = array(
'uploaded' => true,
'message' => 'success',
'description' => 'File successfully uploaded!',
'file' => $slugified_file_name
);
echo json_encode($result);
} else {
throw new RuntimeException('Error: Failed to move uploaded file.');
}
}
catch (RuntimeException $e)
{
$result = array(
'uploaded' => false,
'message' => 'error',
'description' => $e->getMessage()
);
echo json_encode($result);
}
function isValidMD5($md5 ='') {
return strlen($md5) == 32 && ctype_xdigit($md5);
}
function slugify($string)
{
return str_replace('’', '', strtolower(preg_replace('/[^A-Za-z0-9-_]+/', '-', trim($string))));
}
?>