美文网首页
PHP文件上传

PHP文件上传

作者: Fisher123 | 来源:发表于2018-06-27 15:03 被阅读13次

1.创建一个文件上传表单

<html>
<head>
<meta charset="utf-8">
<title>PHP文件上传(runoob.com)</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>

2.创建上传脚本

"upload_file.php" 文件含有供上传文件的代码:
在这个脚本中,用户只能上传 .gif、.jpeg、.jpg、.png 文件,文件大小必须小于 200 kB:

<?php
// 允许上传的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$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"];
    }
    
} else {
    echo "非法的文件格式";
}
?>

相关文章

网友评论

      本文标题:PHP文件上传

      本文链接:https://www.haomeiwen.com/subject/cvgbyftx.html