Home  >  Article  >  Backend Development  >  PHP determines whether the uploaded file is legal

PHP determines whether the uploaded file is legal

angryTom
angryTomOriginal
2019-10-17 16:20:593306browse

PHP determines whether the uploaded file is legal

Sometimes we need to set up the backend so that users can only upload files with specified suffix names. At this time, the files need to be detected.

The code is as follows

/**
 * 获取文件后缀名,并判断是否合法
 *
 * @param string $file_name
 * @param array $allow_type
 * @return blob
*/
function get_file_suffix($file_name, $allow_type = array())
{
	$fnarray=explode('.', $file_name);
	$file_suffix = strtolower(array_pop($fnarray));
	if (empty($allow_type))
	{
		return $file_suffix;
	}
	else
	{
		if (in_array($file_suffix, $allow_type))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

Test

$allow_wj="jpg,gif,png,jpeg";
$allow=explode(",",$allow_wj); 

if (get_file_suffix("sakjdfk1.jpg",$allow)){
	echo "ok";
}else{
	echo "no";
}

Result

ok

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of PHP determines whether the uploaded file is legal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn