php基础练习--文件上传

php基础练习--文件上传:

<html>

<head>

    <meta charset="utf-8">

    <title>uploads_index</title>

</head>

<body>

    <form action="uploads.php" method="post" enctype="multipart/form-data">

        <input type="file" name="file">

        <br>

        <input type="submit" name="" value="upload">

    </form>

</body>

</html>
uploads_index.php
<?php

            

            $tmpfile = $_FILES['file']['tmp_name'];

            $filetype = array_shift(explode("/", $_FILES['file']['type']));   //上传文件的mime类型

            $filename = $_FILES['file']['name'];

            $filefix = array_pop(explode(".", $_FILES['file']['name']));     //上传文件后缀名



            if ($filetype == 'image') {

                $dstfile = "uploads/imgs/".time()."_".mt_rand().".".$filefix;

            } else {

                $dstfile = "uploads/files/".time()."_".mt_rand().".".$filefix;

            }

            



            $filearr = array('gif', 'jpg', 'png');     //允许上传类型

            $filesize = $_FILES['file']['size'];   //上传文件的大小

            $fileerror = $FILES['file']['error'];   //错误编号



            if ($fileerror === 0) {    

                if (in_array($filefix, $filearr)) {     //判断是否符合上传允许类型

                    if ($filesize <= 35840) {          //上传大小限制

                        if (move_uploaded_file($tmpfile, $dstfile)) {

                            echo "<script>alert('succeed!');location.href='uploads_index.php';</script>";

                        } else {

                            echo "<script>alert('fail!');location.href='uploads_index.php';</script>";

                        }

                    } else {

                        echo "<script>alert('pass filesize!');</script>";

                    }

                } else {

                    echo "<script>alert('type fail!');</script>";

                }

            } else {

                echo "<script>alert('error!!!');</script>";

            }
uploads.php

核心:<1>上传首页需要注意form表单中的entype,以及input中type的类型;

   <2>上传页面中文件名后缀、文件的mime的获取;

   <3>注意错误编号。

你可能感兴趣的:(php基础)