zoukankan      html  css  js  c++  java
  • php实现文件上传

    今天用PHP实现一个图片上传功能。踩了几个坑,记录下~

    前台代码

    <form action="index.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>

    方法要用post,必须加上enctype="multipart/form-data"。否则文件无法上传

    后台php部分

    <?php
        $name=$_FILES["file"]["name"];
        $type=$_FILES["file"]["type"];
        $size=$_FILES["file"]["size"];
        $error=$_FILES["file"]["error"];
        $dir='upload/';
        //upload error
        if($error>0){
            echo 'fail to upload';
            exit;
        }
        //type select error
        if($type=='image/gif' || $type == "image/jpeg" || $type == "image/pgpeg" || $type == "image/png"){
    
            //size larger than 30kb
            if($size>30*1024){
                echo 'uploaded is more than 30kb';
                exit;
            }
    
            //make $dir if not exist
            if(!file_exists($dir)){
                mkdir('upload/');
            }
    
            //if upload is exist
    
            if(file_exists('upload/'.$name)){
                echo 'file exist';
            }else{
                  move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$name);
                  echo "upload file complete";
            }
        }else{
            echo 'please send the right files';
            exit;
        }
    ?>

     1.文件上传到临时目录,脚本执行完之后,临时文件就会被删除掉。。(找了好久没找到临时文件,哭)。所以用move_uploaded_file 把临时文件保存到另一个文件下

       2. $error>0就是上传出错,报啥错就放个参考的地址http://php.net/manual/zh/features.file-upload.errors.php

     3.$_FILES["file"] 是个数组,包含'size','name','type','tmp_name'等数据,分别表示上传的文件大小,名字,类型,临时文件名。

       4. file_exists 判断文件是否存在

     5.mkdir新建目录。

    嘿嘿,大概就这些东西了。

  • 相关阅读:
    ●表单元素
    ●HTML网页标签2
    ●数据库的备份
    ●HTML网页标签1
    ●索引、视图、游标
    ●SQL编程
    ●关系数据库基础
    ●常用函数
    ●SQL练习题
    ●SQL高级查询
  • 原文地址:https://www.cnblogs.com/wz0107/p/5107555.html
Copyright © 2011-2022 走看看