Comme ça:
html:
<input type="file" />
PHP:
private function file_upload ($file = null, $dir = null){
try {
if(!file_exists($dir)){
if(!mkdir($dir, 0755, true)){
throw new BadRequestException('Can not mkdir.');
}
chmod($dir, 0755);
}
if (!isset($file['error']) || is_array($file['error'])){
throw new BadRequestException('Invalid parameters.');
}
switch ($file['error']) {
case 0:
break;
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new BadRequestException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new BadRequestException('Exceeded filesize limit.');
default:
throw new BadRequestException('Unknown errors.');
}
$temp = explode('.', $file["name"]);
$extension = end($temp);
//juste jpg ou png
if (false === array_search($extension,['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG'],true)) {
throw new BadRequestException('Invalid file format. '. $file['type']);
}
$uploadFile = sha1(time() . rand()) . "." . $extension;
if (!@move_uploaded_file($file["tmp_name"], $dir . "/" . $uploadFile)){
throw new BadRequestException('Failed to move uploaded file.');
}
} catch (BadRequestException $e) {
throw $e;
}
return $uploadFile;
}
try {
if(!file_exists($dir)){
if(!mkdir($dir, 0755, true)){
throw new BadRequestException('Can not mkdir.');
}
chmod($dir, 0755);
}
if (!isset($file['error']) || is_array($file['error'])){
throw new BadRequestException('Invalid parameters.');
}
switch ($file['error']) {
case 0:
break;
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new BadRequestException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new BadRequestException('Exceeded filesize limit.');
default:
throw new BadRequestException('Unknown errors.');
}
$temp = explode('.', $file["name"]);
$extension = end($temp);
//juste jpg ou png
if (false === array_search($extension,['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG'],true)) {
throw new BadRequestException('Invalid file format. '. $file['type']);
}
$uploadFile = sha1(time() . rand()) . "." . $extension;
if (!@move_uploaded_file($file["tmp_name"], $dir . "/" . $uploadFile)){
throw new BadRequestException('Failed to move uploaded file.');
}
} catch (BadRequestException $e) {
throw $e;
}
return $uploadFile;
}
Aucun commentaire:
Enregistrer un commentaire