[moka同学代码]PHP初级知识:上传文件源码

1.目录结构

     

2.index.php

<html>
<head>
    <meta charset="utf-8">
    <title>上传文件</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file">文件名</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

3.upload.php

<?php
//上传文件代码
//核心代码:
/*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']['tem_name'];
}*/

//上传文件所需要的代码,但是在上传之前需要对文件进行判断限制,大小,类型等

//允许上海窜的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]); //截取文件后缀
$extension = end($temp); //文件后缀
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$error = $_FILES["file"]["error"];
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES["file"]["tmp_name"];
if (($type == "image/gif") || ($type == "image/jpeg") || ($type == "image/jpg") || ($type == "image/pjpeg") ||
    ($type == "image/x-png") || ($type == "image/png") && $size < 2048 && in_array($extension, $allowedExts)
) {
    if ($error > 0) {
        echo "错误:" . $error . '<br>';
    } else {
        echo "文件名称:" . $name . "<br>";
        echo "文件类型:" . $type . "<br>";
        echo "文件大小:" . ($size / 1024) . "kb<br>";
        echo "临时存放位置:" . $tmp_name;

        //判断存放文件的目录中是否存在该文件,如果没有,需要创建它,file的目录权限为777
        if (file_exists("file/" . $name)) {
            echo $name . "文件已经存在。";
        } else {
            move_uploaded_file($tmp_name, 'file/'. $name);
            echo "文件存储在:" . "file/". $name;
        }

    }
} else {
    echo "非法文件";
}
我生活的地方,我为何要生活。
原文地址:https://www.cnblogs.com/hsd1727728211/p/5895683.html