PHP文件上传到服务器
PHP配置文件(php.ini)说明:
;On/Off 开启/关闭文件上传,关闭后$_FILES是个空数组 file_uploads = On ;临时文件存放目录,在PHP处理完成后立即删除该临时文件, ;可以通过sleep(10)来延期处理时间来查看该临时文件。 upload_tmp_dir = D:/phpstudy/Extensions/tmp ;允许上传的最大文件大小(单个文件),可以使用K、M、G单位,超过了的话error为1 upload_max_filesize = 50M ;POST文件大小。总共的,包括上传的文件和一些文本框的总大小。 ;它是要大于等于upload_max_filesize的值的 post_max_size = 50M ;最大上传文件的数量,超出了个数的文件不保存到$_FILES max_file_uploads = 20
单文件上传:
构建前台表单:
<form action="xxx.php" method="post" enctype="multipart/form-data"> <!--限制最大的上传大小,必须放在上传文件input的前面,否知无效。单位:字节; 超过的话error值为2--> <!--<input type="hidden" name="MAX_FILE_SIZE" value="20000">--> <input type="file" name="upfile1"> <input type="file" name="upfile2"> <button>提交</button> </form>
PHP接收:
print_r($_FILES); //想查看临时文件的话可以让程序休息10秒,然后就可以在存放临时文件的目录查看到对应的文件了 //sleep(10);
打印示例:
ERROR详细说明:(注意没有错误编码5)
错误编码 | 常量名称 | 原因 |
0 | UPLOAD_ERR_OK | 没有错误发生,文件上传成功。 |
1 | UPLOAD_ERR_INI_SIZE | 上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值。 |
2 | UPLOAD_ERR_FORM_SIZE | 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 |
3 | UPLOAD_ERR_PARTIAL | 文件只有部分被上传。 |
4 | UPLOAD_ERR_NO_FILE | 没有文件被上传。 |
6 | UPLOAD_ERR_NO_TMP_DIR | 找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。 |
7 | UPLOAD_ERR_CANT_WRITE | 文件写入失败。PHP 5.1.0 引进。 |
文件上传的关键函数介绍:
函数名 | 作用 | 参数 | 返回值 |
is_uploaded_file | 检查指定的文件是否是通过 HTTP POST 上传的。 | string $filename 必须 规定要检查的文件。 | bool |
move_uploaded_file | 把上传的文件移动到新位置。 | string $filename 必须 规定要移动的文件。 | bool |
string $destination 必须
规定文件的新位置。 注意:如果填写绝对路径,则路径是操作系统的文件系统的绝对路径,并不是网站的根目录开始。 |
上传文件的保存:
// 判断是不是上传的文件 if (is_uploaded_file($_FILES['upfile1']['tmp_name'])) { // 过滤文件类型&文件大小 // 根据$_FILES['upfile1']['type']和$_FILES['upfile1']['size']自行处理即可... // 判断是否上传成功 switch ($_FILES['upfile1']['error']) { case 0:echo '文件上传成功。'; // 创建目录保存,位置和规则自定义 $path = './files/'.date('Y-m'); // 更改新的文件名,否则文件名重复会覆盖之前的文件。 // 这里是直接用哈希值,可以自行改为:先判断这个文件是否存在,若存在则改名字保存。 $file_name = md5(mt_rand(111,999)).$_FILES['upfile1']['name']; if (is_dir($path) or mkdir($path,0755,true)){ // 移动文件到你要保存的目录 if (move_uploaded_file($_FILES['upfile1']['tmp_name'], $path.'/'.$file_name)) { echo '移动成功'; }else{ echo '移动失败'; } }else{ echo '创建目录失败'; } break; case 1:echo '上传的文件超过了php.ini中upload_max_filesize选项限制的值。';break; case 2:echo '上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值。';break; case 3:echo '文件只有部分被上传。';break; case 4:echo '没有文件被上传。';break; case 6:echo '找不到临时文件夹。';break; case 7:echo '文件写入失败。';break; default:echo '未知错误'; } }
多文件上传:
前端表单:
<form action="xxx.php" method="post" enctype="multipart/form-data"> <!--将input的name后面加上[],变为数组模式提交--> <input type="file" name="upfile1"> <input type="file" name="upfile[]"> <input type="file" name="upfile[]"> <button>提交</button> </form>
打印示例:
数据处理
由于这种格式并不方便我们对上传的文件进行遍历,故封装了一个函数,对这个数组进行一下格式化的处理。
/** * @param array $arr * @return array */ function format_arr(array $arr): array { $format = array(); foreach ($arr as $value) { if (is_array($value['name'])) { foreach ($value['name'] as $item => $val) { $format[] = array( 'name' => $value['name'][$item], 'type' => $value['type'][$item], 'error' => $value['error'][$item], 'tmp_name' => $value['tmp_name'][$item], 'size' => $value['size'][$item] ); } } else { $format[] = $value; } } return $format; }
打印示例:
上传文件的保存:
此时只需要遍历整个格式化后的数组即可。
$arr = format_arr($_FILES); //这个函数在前面定义了 foreach ($arr as $value){ if (is_uploaded_file($value['tmp_name'])) { // 过滤文件类型&文件大小 // 根据$_FILES['upfile1']['type']和$_FILES['upfile1']['size']自行处理即可... // 判断是否上传成功 switch ($value['error']) { case 0:echo '文件上传成功。'; // 创建目录保存,位置和规则自定义 $path = './files/'.date('Y-m'); // 更改新的文件名,否则文件名重复会覆盖之前的文件。 // 这里是直接用哈希值,可以自行改为:先判断这个文件是否存在,若存在则改名字保存。 $file_name = md5(mt_rand(111,999)).$value['name']; if (is_dir($path) or mkdir($path,0755,true)){ // 移动文件到你要保存的目录 if (move_uploaded_file($value['tmp_name'], $path.'/'.$file_name)) { echo '移动成功'; }else{ echo '移动失败'; } }else{ echo '创建目录失败'; } break; case 1:echo '上传的文件超过了php.ini中upload_max_filesize选项限制的值。';break; case 2:echo '上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值。';break; case 3:echo '文件只有部分被上传。';break; case 4:echo '没有文件被上传。';break; case 6:echo '找不到临时文件夹。';break; case 7:echo '文件写入失败。';break; default:echo '未知错误'; } } }
PHP通过cURL传输文件
首先封装了个cURL的方法
/** * @param string $url * @param null $data * @param bool $isUsePost * @param array $header * @return bool|int|string */ function curl_http_send($url = '', $data = NULL, $isUsePost = true, $header = []) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if ($isUsePost) { curl_setopt($curl, CURLOPT_POST, true); } curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $res = curl_exec($curl); $errorNO = curl_errno($curl); curl_close($curl); if ($errorNO) { return $errorNO; } return $res; }
$URL = '/send/to/where';//接口地址 $path = '/your/file/path/xxx.png'; // 文件路径 $send_data = ['file'=>curl_file_create($path)]; // 同样,前面的键就是前端的name。或者说是看对方接口需要的名字 // 在PHP5.5版本以前的版本,需要使用@拼接要传输的文件的绝对路径即可(没测试过,有时间可以自己试试) // $send_data = ['file'=> '@'.$path]; $return = curl_http_send($URL,$send_data,true,['Content-Type:multipart/form-data']); var_dump($return);
函数介绍:
函数名 | 作用 | 参数 | 返回值 |
curl_file_create | 创建一个 CURLFile 对象, 用与上传文件。 | string $filename 必须上传文件的路径 | 返回 CURLFile 对象。(https://secure.php.net/manual/en/class.curlfile.php) |
string $mimetype 选填文件的Mimetype | |||
string $postname 选填文件名 |
后记:
关于PHP的文件上传就完成了,当然这个只是用于学习,实际开发当中,前端一般会使用一些上传的组件,既美观又方便。后端一般都是使用别人或者框架封装好的类。不过学了这些,其实可以自己动手封装一个文件上传类了。
作者:蓝天 lantx
2019-10-17
附:上传文件类型对应的type(Mimetype)
3gp video/3gpp aab application/x-authoware-bin aam application/x-authoware-map aas application/x-authoware-seg ai application/postscript aif audio/x-aiff aifc audio/x-aiff aiff audio/x-aiff als audio/X-Alpha5 amc application/x-mpeg ani application/octet-stream asc text/plain asd application/astound asf video/x-ms-asf asn application/astound asp application/x-asap asx video/x-ms-asf au audio/basic avb application/octet-stream avi video/x-msvideo awb audio/amr-wb bcpio application/x-bcpio bin application/octet-stream bld application/bld bld2 application/bld2 bmp application/x-MS-bmp bpk application/octet-stream bz2 application/x-bzip2 cal image/x-cals ccn application/x-cnc cco application/x-cocoa cdf application/x-netcdf cgi magnus-internal/cgi chat application/x-chat class application/octet-stream clp application/x-msclip cmx application/x-cmx co application/x-cult3d-object cod image/cis-cod cpio application/x-cpio cpt application/mac-compactpro crd application/x-mscardfile csh application/x-csh csm chemical/x-csml csml chemical/x-csml css text/css cur application/octet-stream dcm x-lml/x-evm dcr application/x-director dcx image/x-dcx dhtml text/html dir application/x-director dll application/octet-stream dmg application/octet-stream dms application/octet-stream doc application/msword dot application/x-dot dvi application/x-dvi dwf drawing/x-dwf dwg application/x-autocad dxf application/x-autocad dxr application/x-director ebk application/x-expandedbook emb chemical/x-embl-dl-nucleotide embl chemical/x-embl-dl-nucleotide eps application/postscript eri image/x-eri es audio/echospeech esl audio/echospeech etc application/x-earthtime etx text/x-setext evm x-lml/x-evm evy application/x-envoy exe application/octet-stream fh4 image/x-freehand fh5 image/x-freehand fhc image/x-freehand fif image/fif fm application/x-maker fpx image/x-fpx fvi video/isivideo gau chemical/x-gaussian-input gca application/x-gca-compressed gdb x-lml/x-gdb gif image/gif gps application/x-gps gtar application/x-gtar gz application/x-gzip hdf application/x-hdf hdm text/x-hdml hdml text/x-hdml hlp application/winhlp hqx application/mac-binhex40 htm text/html html text/html hts text/html ice x-conference/x-cooltalk ico application/octet-stream ief image/ief ifm image/gif ifs image/ifs imy audio/melody ins application/x-NET-Install ips application/x-ipscript ipx application/x-ipix it audio/x-mod itz audio/x-mod ivr i-world/i-vrml j2k image/j2k jad text/vnd.sun.j2me.app-descriptor jam application/x-jam jar application/java-archive jnlp application/x-java-jnlp-file jpe image/jpeg jpeg image/jpeg jpg image/jpeg jpz image/jpeg js application/x-javascript jwc application/jwc kjx application/x-kjx lak x-lml/x-lak latex application/x-latex lcc application/fastman lcl application/x-digitalloca lcr application/x-digitalloca lgh application/lgh lha application/octet-stream lml x-lml/x-lml lmlpack x-lml/x-lmlpack lsf video/x-ms-asf lsx video/x-ms-asf lzh application/x-lzh m13 application/x-msmediaview m14 application/x-msmediaview m15 audio/x-mod m3u audio/x-mpegurl m3url audio/x-mpegurl ma1 audio/ma1 ma2 audio/ma2 ma3 audio/ma3 ma5 audio/ma5 man application/x-troff-man map magnus-internal/imagemap mbd application/mbedlet mct application/x-mascot mdb application/x-msaccess mdz audio/x-mod me application/x-troff-me mel text/x-vmel mi application/x-mif mid audio/midi midi audio/midi mif application/x-mif mil image/x-cals mio audio/x-mio mmf application/x-skt-lbs mng video/x-mng mny application/x-msmoney moc application/x-mocha mocha application/x-mocha mod audio/x-mod mof application/x-yumekara mol chemical/x-mdl-molfile mop chemical/x-mopac-input mov video/quicktime movie video/x-sgi-movie mp2 audio/x-mpeg mp3 audio/x-mpeg mp4 video/mp4 mpc application/vnd.mpohun.certificate mpe video/mpeg mpeg video/mpeg mpg video/mpeg mpg4 video/mp4 mpga audio/mpeg mpn application/vnd.mophun.application mpp application/vnd.ms-project mps application/x-mapserver mrl text/x-mrml mrm application/x-mrm ms application/x-troff-ms mts application/metastream mtx application/metastream mtz application/metastream mzv application/metastream nar application/zip nbmp image/nbmp nc application/x-netcdf ndb x-lml/x-ndb ndwn application/ndwn nif application/x-nif nmz application/x-scream nokia-op-logo image/vnd.nok-oplogo-color npx application/x-netfpx nsnd audio/nsnd nva application/x-neva1 oda application/oda oom application/x-AtlasMate-Plugin pac audio/x-pac pae audio/x-epac pan application/x-pan pbm image/x-portable-bitmap pcx image/x-pcx pda image/x-pda pdb chemical/x-pdb pdf application/pdf pfr application/font-tdpfr pgm image/x-portable-graymap pict image/x-pict pm application/x-perl pmd application/x-pmd png image/png pnm image/x-portable-anymap pnz image/png pot application/vnd.ms-powerpoint ppm image/x-portable-pixmap pps application/vnd.ms-powerpoint ppt application/vnd.ms-powerpoint pqf application/x-cprplayer pqi application/cprplayer prc application/x-prc proxy application/x-ns-proxy-autoconfig ps application/postscript ptlk application/listenup pub application/x-mspublisher pvx video/x-pv-pvx qcp audio/vnd.qcelp qt video/quicktime qti image/x-quicktime qtif image/x-quicktime r3t text/vnd.rn-realtext3d ra audio/x-pn-realaudio ram audio/x-pn-realaudio rar application/x-rar-compressed ras image/x-cmu-raster rdf application/rdf+xml rf image/vnd.rn-realflash rgb image/x-rgb rlf application/x-richlink rm audio/x-pn-realaudio rmf audio/x-rmf rmm audio/x-pn-realaudio rmvb audio/x-pn-realaudio rnx application/vnd.rn-realplayer roff application/x-troff rp image/vnd.rn-realpix rpm audio/x-pn-realaudio-plugin rt text/vnd.rn-realtext rte x-lml/x-gps rtf application/rtf rtg application/metastream rtx text/richtext rv video/vnd.rn-realvideo rwc application/x-rogerwilco s3m audio/x-mod s3z audio/x-mod sca application/x-supercard scd application/x-msschedule sdf application/e-score sea application/x-stuffit sgm text/x-sgml sgml text/x-sgml sh application/x-sh shar application/x-shar shtml magnus-internal/parsed-html shw application/presentations si6 image/si6 si7 image/vnd.stiwap.sis si9 image/vnd.lgtwap.sis sis application/vnd.symbian.install sit application/x-stuffit skd application/x-Koan skm application/x-Koan skp application/x-Koan skt application/x-Koan slc application/x-salsa smd audio/x-smd smi application/smil smil application/smil smp application/studiom smz audio/x-smd snd audio/basic spc text/x-speech spl application/futuresplash spr application/x-sprite sprite application/x-sprite spt application/x-spt src application/x-wais-source stk application/hyperstudio stm audio/x-mod sv4cpio application/x-sv4cpio sv4crc application/x-sv4crc svf image/vnd svg image/svg-xml svh image/svh svr x-world/x-svr swf application/x-shockwave-flash swfl application/x-shockwave-flash t application/x-troff tad application/octet-stream talk text/x-speech tar application/x-tar taz application/x-tar tbp application/x-timbuktu tbt application/x-timbuktu tcl application/x-tcl tex application/x-tex texi application/x-texinfo texinfo application/x-texinfo tgz application/x-tar thm application/vnd.eri.thm tif image/tiff tiff image/tiff tki application/x-tkined tkined application/x-tkined toc application/toc toy image/toy tr application/x-troff trk x-lml/x-gps trm application/x-msterminal tsi audio/tsplayer tsp application/dsptype tsv text/tab-separated-values tsv text/tab-separated-values ttf application/octet-stream ttz application/t-time txt text/plain ult audio/x-mod ustar application/x-ustar uu application/x-uuencode uue application/x-uuencode vcd application/x-cdlink vcf text/x-vcard vdo video/vdo vib audio/vib viv video/vivo vivo video/vivo vmd application/vocaltec-media-desc vmf application/vocaltec-media-file vmi application/x-dreamcast-vms-info vms application/x-dreamcast-vms vox audio/voxware vqe audio/x-twinvq-plugin vqf audio/x-twinvq vql audio/x-twinvq vre x-world/x-vream vrml x-world/x-vrml vrt x-world/x-vrt vrw x-world/x-vream vts workbook/formulaone wav audio/x-wav wax audio/x-ms-wax wbmp image/vnd.wap.wbmp web application/vnd.xara wi image/wavelet wis application/x-InstallShield wm video/x-ms-wm wma audio/x-ms-wma wmd application/x-ms-wmd wmf application/x-msmetafile wml text/vnd.wap.wml wmlc application/vnd.wap.wmlc wmls text/vnd.wap.wmlscript wmlsc application/vnd.wap.wmlscriptc wmlscript text/vnd.wap.wmlscript wmv audio/x-ms-wmv wmx video/x-ms-wmx wmz application/x-ms-wmz wpng image/x-up-wpng wpt x-lml/x-gps wri application/x-mswrite wrl x-world/x-vrml wrz x-world/x-vrml ws text/vnd.wap.wmlscript wsc application/vnd.wap.wmlscriptc wv video/wavelet wvx video/x-ms-wvx wxl application/x-wxl x-gzip application/x-gzip xar application/vnd.xara xbm image/x-xbitmap xdm application/x-xdma xdma application/x-xdma xdw application/vnd.fujixerox.docuworks xht application/xhtml+xml xhtm application/xhtml+xml xhtml application/xhtml+xml xla application/vnd.ms-excel xlc application/vnd.ms-excel xll application/x-excel xlm application/vnd.ms-excel xls application/vnd.ms-excel xlt application/vnd.ms-excel xlw application/vnd.ms-excel xm audio/x-mod xml text/xml xmz audio/x-mod xpi application/x-xpinstall xpm image/x-xpixmap xsit text/xml xsl text/xml xul text/xul xwd image/x-xwindowdump xyz chemical/x-pdb yz1 application/x-yz1 z application/x-compress zac application/x-zaurus-zac zip application/zip