1 文件上传

1.1    机制

当上传一个文件时,会先将其作为临时目录传到服务器,如果不将其启动到其它目录,就会删除。

1.2    需要使用的东西

<form action="upload.php" method="post"

enctype="multipart/form-data">

<input type="file">

l  在表单里写个输入类型为file

l  还需要添加enctype="multipart/form-data"

详情查手册:POST方法上传

上传的表单界面

<!DOCTYPE html>

<html lang="zh-cn">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>上传文件</title>

</head>

<body>

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

        用户名:<input type="text" name="uName"><br />

        <!-- 对于浏览器的建议,设置文件大小 -->

        <input type="hidden" name="MAX_FILE_SIZE" value="30000">

        文件:<input type="file" name="img">

        <input type="submit" value="提交">

    </form>

</body>

</html>

php上传后端:upload.php

<?php

$uName =$_POST['uName'];

echo $uName.'<br/>';

//1.首先判断是否出错

if($_FILES['userfile']['error'] > 0){

    switch($_FILES['userfile']['error']){

        case 1:

            die('上传文件超过了php.ini中upload_max_filesize选项限制的值。');

        case 2:

            die('上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。');

        case 3:

            die('文件只有部分被上传。');

        case 4:

            die('文件没有被上传');

        case 6:

            die('找不到临时文件');

        case 7:

            die('文件写入失败');

    }

}

//2.判断上传类型是否符合规定

echo $_FILES['userfile']['type'];

$type = array('image/jpeg','image/png','image/gif');//允许的格式

if(!in_array($_FILES['userfile']['type'],$type)){

    die('别给我乱传东西。');

}

//3.判断所传文件大小是否在运许之内

$size = 300000;

if($_FILES['userfile']['size'] > $size){

    die('文件过大,别搞啊。');

}

//4.制作上传的目录

$uploaddir = 'D:/phpstudy/phpstudy_pro/WWW/test/文件上传实例/upload';

if(!file_exists($uploaddir)){

    mkdir($uploaddir);

}

//5.重命名文件

//(1)先获取后缀名,突然感觉我不想这么做

//$suffix = strrchr($_FILES['userfile']['name'],'.');

do{

    $name = md5(time()).$_FILES['userfile']['name'];

}while(file_exists($uploaddir.'/'.$name));

//6.移动文件

echo $name;

if(move_uploaded_file($_FILES['userfile']["tmp_name"],$uploaddir.'/'.$name)){

    echo "上传成功。";

}else{

    echo "上传失败";

}

?>

 

posted @ 2022-03-05 15:15  xiaoovo  阅读(39)  评论(0)    收藏  举报