PHP 文件上传到服务器

版权声明: https://blog.csdn.net/qq_23521659/article/details/87873801

 

代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data">
    <lable for="file">文件:</lable>
    <input type="file" name="file" id="file">
    <input type="submit" value="提交">
</form>
</body>
</html>
<?php
/**
 * Created by PhpStorm.
 * User: wangyangyang
 * Date: 2019/2/22
 * Time: 9:24
 */

/**
 * $_SERVER["PHP_SELF"]是超级全局变量,返回当前正在执行脚本的文件名,与 document root相关。
 *
 * htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。 避免xss攻击
 *
 * enctype 属性规定了在提交表单时要使用哪种内容类型。在表单需要二进制数据时,比如文件内容,请使用 "multipart/form-data"。
 *
 * in_array  数组中搜索值 "xxx"
 *
 * file_exists() 函数检查文件或目录是否存在。
 *
 * move_uploaded_file() 函数将上传的文件移动到新位置。
 *
 */

$allowedExts = array("gif","png","jpg","jpeg");

// explode 把字符串打散为数组 目的是为了获取文件名后缀
$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/jpeg")||
    ($_FILES["file"]["type"] == "image/x-png")||
    ($_FILES["file"]["type"] == "image/png"))
     && ($_FILES["file"]["size"] < 20000)  //限制大小 20kb
    && in_array($extension, $allowedExts)  //限制后缀名
){
    if ($_FILES['file']["error"] > 0) {
        echo "Error" . $_FILES['file']["error"] . "<br>";
    } else {
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"];

        if(file_exists("upload/".$_FILES["file"]["name"])){
            echo $_FILES["file"]["name"]."文件已存在!";
        }else{
            move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
            echo "文件路径:"."upload/".$_FILES["file"]["name"];
        }

    }

}else{
    echo "文件类型不支持!";
}



$_SERVER["PHP_SELF"]是超级全局变量,返回当前正在执行脚本的文件名,与 document root相关。

 htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。 避免xss攻击。

enctype 属性规定了在提交表单时要使用哪种内容类型。在表单需要二进制数据时,比如文件内容,请使用 "multipart/form-data"。

 in_array  数组中搜索值 "xxx"

 file_exists() 函数检查文件或目录是否存在。

move_uploaded_file() 函数将上传的文件移动到新位置。

最终效果:

猜你喜欢

转载自blog.csdn.net/qq_23521659/article/details/87873801