php中上传图片文件的PHP函数
在php中上传图片我们全结合$_files 与move_uploaded_file函数来一起操作,从而实现从客户端把文件上传到服务器端了,下面一起来看看具体的操作子.
编程环境
PHP5.2.4,基本上PHP4.3以上版本,此代码都可以使用.
准备工作
检查upload_tmp_dir项
如果PHP的开发环境是自行搭建的,你需要在编写文件上传程序前编辑php.ini文件,找到并编辑upload_tmp_dir选项,此项用来设定文件上传至服务器时的临时文件夹,比如upload_tmp_dir = E:/phpos/uploads,然后再重启Apache,如果PHP的开发环境使用的是傻瓜式一键安装包,一般upload_tmp_dir都是设定好了的,你也可以用phpinfo()函数查看下配置.
PHP实例代码如下:
<input name="userfile" type="file"> <?php if (!emptyempty($_FILES['file']['name'])) { $img = $this->up_file("file"); } //up_file()函数 function up_file($inputname, $destinate = "../data/agency/", $type = "", $maxSize = 0) { $arr = explode('.', $_FILES[$inputname]['name']); $count = count($arr); $typearr = explode(',', $type); if (!emptyempty($type)) { if (!in_array($arr[$count - 1], $typearr)) { $this->show_warning('文件类型不允许上传'); exit(); } } if ($maxSize != 0) { if (($_FILES[$inputname]['size'] / 1000) >= $maxSize) { $this->show_warning('文件大小超过限制'); exit(); } } if (!emptyempty($destinate)) { $destinate = substr(str_replace("", "/", $destinate) , -1) == "/" ? $destinate : $destinate . "/"; if (!is_writable($destinate)) { $this->show_warning('文件目录发生错误'); exit(); } } $filename = date("YmdHis") . (microtime() * 1000000) . "." . $arr[$count - 1]; if (is_file($destinate . $filename)) { up_file($inputname, $destinate = "", $type = "", $maxSize = 0); } else { $filename = $filename; } copy($_FILES[$inputname]['tmp_name'], $destinate . $filename); @unlink($_FILES[$inputname]['tmp_name']); return $filename; } ?>
以上范例中 $_FILES 数组的内容如下所示,我们假设文件上传字段的名称为 userfile(名称可随意命名)
如何上传多个文件?比如同时上传3个文件,只需将如下代码:
<input name="userfile" type="file"> 改成
<input name="userfile[]" type="file">
<input name="userfile[]" type="file">
<input name="userfile[]" type="file">
对应的在调用此函数时,$_FILES['userfile']['name'][0],代表第一个文件的相关文件信息,依此类推,其他也一样.
$_FILES['userfile']['name'] 客户端机器文件的原名称.
$_FILES['userfile']['type'] 文件的 MIME 类型,需要浏览器提供该信息的支持,例如“image/gif”.
$_FILES['userfile']['size'] 已上传文件的大小,单位为字节。
$_FILES['userfile']['tmp_name'] 文件被上传后在服务端储存的临时文件名。
$_FILES['userfile']['error'] 和该文件上传相关的错误代码
值:0; 没有错误发生,文件上传成功。
值:1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
值:2; 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
值:3; 文件只有部分被上传。
值:4; 没有文件被上传。
上传大文件失败的解决办法:
文件上传时存放文件的临时目录必须是开启的并且是 PHP 进程所有者用户可写的目录,如果未指定则 PHP 使用系统默认值.
max_execution_time = 90
file_uploads = On
upload_max_filesize = 2M 设定文件上传的大小的最大值.
本文地址:http://www.phprm.com/scxz/fs3234.html
转载随意,但请附上文章地址:-)