Home >Backend Development >PHP Tutorial >如果用PHP给上传的文件改成其MD5值且保留后缀名

如果用PHP给上传的文件改成其MD5值且保留后缀名

WBOY
WBOYOriginal
2016-06-06 20:21:101694browse

假设我用php接收表单上传的文件,怎么实现给上传的文件改名(改成其文件md5值,以防止重名),而且保留后缀。
最好能给一段示例代码

回复内容:

假设我用php接收表单上传的文件,怎么实现给上传的文件改名(改成其文件md5值,以防止重名),而且保留后缀。
最好能给一段示例代码

假设表单如此:

<code class="HTML"><form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="form_file_name" id="file"> 
<br>
<input type="submit" name="submit" value="Submit">
</form></code>
<code class="PHP"><?php // 检查错误什么的就不写了
$filename = $_FILES['form_file_name']["tmp_name"];
$md5 = md5_file($filename);
$ext = pathinfo($_FILES['form_file_name']['name'], PATHINFO_EXTENSION);
move_uploaded_file($filename, $md5.'.'.$ext);
?></code>

这样可以换名字:
$str=’test.name’;
$pos=strrpos($str,’.’);
echo substr_replace($str,md5(substr($str,0,$pos)),0,$pos);
手机写代码好费劲。。。

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