HTML文件上传表单
<html>
<head>
<meta charset="utf-8">
<title>PHP </title>
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"> </label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value=" ">
</form>
</body>
</html>
创建上传脚本
<?php
if ($_FILES["file"]["error"] > 0) {
echo "错误:".$_FILES["files"]["error"]."<br>";
}else {
echo "上传文件名:".$_FILES["file"]["name"]."<br>";
echo "文件类型:".$_FILES["file"]["type"]."<br>";
echo "文件大小:".$_FILES["file"]["size"]."kB<br>";
echo "文件临时存储的位置:".$_FILES["file"]["tmp_name"];
}
?>
上传限制和保存上传文件
<?php
//允许上传的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
echo $_FILES["file"]["size"];
$extension = end($temp); //获取文件后缀名
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 204800) //小于200 kb
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0)
{
echo "错误 : " . $_FILES["file"]["error"] . "<br>";
}
else {
echo " : " . $_FILES["file"]["name"] . "<br>";
echo " : " . $_FILES["file"]["type"] . "<br>";
echo " : " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo " : " . $_FILES["file"]["tmp_name"] . "<br>";
//判断当期目录下的upload目录是否存在该文件
//如果没有upload目录,你需要创建它,upload目录权限为777
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " ";
}else {
//如果upload目录不存在该文件则将文件上传到upload目录下
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES
echo "文件储存在: " . "upload/" . $_FILES["file"]["name"];
}
}
}else {
echo "非法的文件格式";
}
?>
上传多个文件
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>