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新建目录。

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

  • 相关阅读:
    jQuery中deferred对象的使用(一)
    css中calc()的使用
    网络协议学习笔记1
    iOS: 类目里动态关联对象
    [转载] 2016 app 上线流程
    iOS:集成环信3.0循环掉坑。(学习笔记一)
    iOS 实现条件选择框
    iOS : 定义项目中接口文档
    iOS:消除项目中的警告⚠️
    iOS 一个简洁的条件筛选界面
  • 原文地址:https://www.cnblogs.com/wz0107/p/5107555.html
Copyright © 2011-2022 走看看