Facebook

Sunday, December 6, 2015

php file upload: clean name of uploaded file, check for duplicate


File upload: clean name of uploaded file, check for duplicate
$config['upload_path'] = DIR_UPLOAD_BANNER;

$file_parts = pathinfo($_FILES['cms_banner_image']['name']);

//Clean file name, replace all specialcharacters with dahs "-" $file_name = preg_replace('/[^A-Za-z0-9\-]/', '', $file_parts['filename']);

//Replace multiple dash with single $file_name = preg_replace('/-+/', '-', $file_name); $config['file_name'] = $file_name.'.'.$file_parts['extension'];

//Check for duplicate file names $counter = 0;
while (file_exists($config['upload_path'].$config['file_name'])) {
    $counter++;
    $config['file_name'] = $file_name.'_'.
                           $counter.'.'.
                           $file_parts['extension'];
}

No comments:

Post a Comment