<?php

################################################ FUNCTION: file_process_upload #
function file_process_upload($input_name,$save_path,$overwrite = false,$replace_regex = "/[^A-Za-z0-9]+/")
{
	$no_errs = true;
	$clean_names = array();
	if(!is_dir($save_path))
	{
		trigger_error('Path is not a directory.',E_USER_ERROR);
		return false;
	}
	
	if(!is_array($_FILES[$input_name]['tmp_name']))
	{
		foreach($_FILES[$input_name] as $key => $value)
			$_FILES[$input_name][$key] = array($_FILES[$input_name][$key]);
	}
		
	foreach($_FILES[$input_name]['tmp_name'] as $key => $value)
	{
		if(!is_uploaded_file($_FILES[$input_name]['tmp_name'][$key]))
		{	
			$no_errs = false;
			trigger_error('File "'.$_FILES[$input_name]['name'][$key].'" is not an uploaded file.',E_USER_ERROR);
		}
		
		$clean_name = $_FILES[$input_name]['name'][$key];
		# find the extension
		preg_match("/(\.\S+)$/",$clean_name,$matches);
		$ext = $matches[1];
		# take the extension off of the file name
		$clean_name = str_replace($ext,'',$clean_name);
		$clean_name = preg_replace($replace_regex,'_',$clean_name);
	
		# move the uploaded file to the new location, unless a file with the same name
		# is already there
		if(file_exists($save_path.'/'.$clean_name.$ext) and !$overwrite)
		{
			$no_errs = false;
			trigger_error('File "'.$_FILES[$input_name]['name'][$key].'" already exists.', E_USER_ERROR);
		}
		if(move_uploaded_file($_FILES[$input_name]['tmp_name'][$key],$save_path.'/'.$clean_name.$ext))
			array_push($clean_names,$clean_name.$ext);
		else
		{
			$no_errs = false;
			trigger_error('File "'.$_FILES[$input_name]['name'][$key].'" could not be moved to permanent location.', E_USER_ERROR);
		}
	}

	if(count($clean_names) == 1)
		return($clean_names[0]);
	else
		return($clean_names);
}

?>