PHP单文件和多文件的上传(示例)
PHP的单文件上传
html文件创建表单
<form action="test7-2.php" method="post" enctype="multipart/form-data">
<table border="1">
<tr>
<th align="center" bgcolor="gray" colspan="2">文件上传实例</th>
</tr>
<tr>
<td>
<span>*</span>文件上传地址:
</td>
<td>
<input type="file" name="file"> (大小《2M为宜)
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="up" value="提交">
<input type="reset" name="reset" value="重置">
</td>
</tr>
</table>
</form>
php文件
if (isset($_POST['up'])) {
if ($_FILES['file']['type'] == 'image/jpg' || $_FILES['file']['type'] == 'image/png' || $_FILES['file']['type'] == "image/png") {
if ($_FILES['file']['error'] > 0) {
echo "错误!:" . $_FILES['file']['error'];
} else {
$tmp_filename = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$dir = "../test/";
if (is_uploaded_file($tmp_filename)) {
if (move_uploaded_file($tmp_filename, "$dir.$filename")) {
echo "文件上传成功!<br>";
echo "文件大小为:" . ($_FILES['file']['size'] / 1024) . "KB";
} else {
echo "上传失败...";
}
}
}
} else {
echo "文件格式非jpg、png、gif格式!请重新上传~";
}
PHP的多文件上传,
html文件创建表单
<form action="test7-3.php" method="post" enctype="multipart/form-data">
<table border="1">
<tr>
<th align="center" bgcolor="gray" colspan="2">文件上传实例</th>
</tr>
<tr>
<td width="150px;">
<span>*</span>文件上传地址:(大小《2M为宜)
</td>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
// 因为是多文件上传,这里的name值里边,需要弄成数组形式,方便php代码中循环遍历文件
// multiple是控制多文件一起上传,即打开文件时,同时选中多个需要上传的文件
<input type="file" name="file[]" multiple="multiple">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="up" value="提交">
<input type="reset" name="reset" value="重置">
</td>
</tr>
</table>
</form>
php文件
if (isset($_POST['up'])) {
for ($i = 0; $i < count($_FILES['file']['tmp_name']); $i++) {
copy($_FILES['file']['tmp_name'][$i], '../test/' . $_FILES['file']['name'][$i]);
echo "文件上传成功!<br>";
echo "文件存储在:" . "../test/" . $_FILES['file']['name'][$i] . "<br>";
var_dump($_FILES['file']['name'][$i]);
}
} else {
echo "文件上传错误,请重新上传~";
}
关于文件的格式问题
后期将会整理关于php上传格式的问题,目前不做详细处理
本篇内容纯属原创,转载记得加上源地址哦
https://www.cnblogs.com/hleisurely/