这篇文章主要介绍了使用php接受文件并获得其后缀名的方法,作者着重提到了其中$_files全局变量的使用,需要的朋友可以参考下
html的form表单
用html的表单模拟一个文件上传的post请求,代码如下:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>file upload</title> </head> <body> <form enctype="multipart/form-data" action="test.php" method="post"> <input type="hidden" name="max_file_size" value="30000" /> send this file:<input name="userfile" type="file"/> <input type="submit" value="send file" /> </form> </body> </html>
注意:
要确保文件上传表单的属性是 enctype="multipart/form-data",否则文件上传不了
php
首先,需要解释一下php的全局变量$_files,此数组包含了所有上传的文件信息
$_file['userfile']['name'] : 客户端机器文件的原名称
$_file['userfile']['type'] : 文件的mime类型
$_file['userfile']['size'] : 已上传的文件大小
$_file['userfile']['tmpname'] : 文件被上传后在服务器存储的临时文件名
$_file['userfile']['error'] : 和该文件上传的错误代码
思路
1、生成40位的随机字符串作为文件名
2、根据文件是图片还是语音转存到不同的文件位置
3、暂时不做文件大小和文件类型的校验
function processfile($files, $type) { $uploadname = null; foreach ($files as $name => $value) { $originalname = $value['name']; $arr = explode(".", $originalname); $postfix = $arr[count($arr) - 1]; $tmppath = $value['tmp_name']; $tmptype = $value['type']; $tmpsize = $value['size']; } $newname = ehlstaticfunction::generaterandomstr(40).".".$postfix; switch ($type) { case 1 : // 处理声音文件 $destination = videouploaddir.$newname; break; case 2 : // 处理图像文件 $destination = imageuploaddir.$newname; break; } move_uploaded_file($tmppath, $destination); }
而获取所上传文件的后缀名则可以使用一下代码:
html
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title></title> <meta name="keywords" content=" keywords" /> <meta name="description" content="description" /></head><body> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="upfile" size="20" /> <input type="submit" name="submit" value="submit" /> </form></body></html>
php
<?php if(isset($_post['submit'])) { $string = strrev($_files['upfile']['name']); $array = explode('.',$string); echo $array[0]; } ?>
结果示例:
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
php使用preg_split和explode实现分割textarea存放内容的方法
php实现文件锁加锁、解锁方法
php实现基于cookie设置用户30分钟未操作自动退出功能的方法
以上就是php接受文件并获取后缀名的方法的详细内容。