Save uploaded file to an given folder

If you use PHP upload file to web server, you have to move the uploaded file from the temp directory to a given folder. Here is generic PHP function to fulfill this job. The function does not need any input parameters but return the save filename. The filename is automatically generated based system date and time. The additional function can find the file extension from the input filename.

Source code

function findexts($filename)
{
	$filename = strtolower($filename) ;
	$exts = split("[/\\.]", $filename) ;
	$n = count($exts)-1;
	$exts = $exts[$n];
	return ".".$exts;
}

function savefile()
{
	// Edit upload location here
	$filename = date('YmdHis').findexts(basename($_FILES['myfile']['name']));
	$target_path = getcwd()."/www-content/".$filename;
	if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
	// do nothing
	}

	return $filename;
}
  • Share/Bookmark

Leave a Response

You must be logged in to post a comment.