zoukankan      html  css  js  c++  java
  • php 文件上传方法

    <?php

    /*
    * 验证错误
     * 如果没有错 就返回空  
     * 有错返回错误信息
     */ 
    function check($file){

        // 1. 验证是否有误 
        if($file['error'] != 0){
            switch($file['error']) {
                case 1:
                    return "文件大小超过了PHP.ini允许的最大值,最大值是:".ini_get('upload_max_filesize'); 
                case 2:
                    return "文件超过了表单允许的最大值"; 
                case 3:
                    return '只有部分文件上传'; 
                case 4:
                    return '没有文件上传'; 
                case 6:
                    return '找不到临时文件'; 
                case 7:
                    return '文件写入失败'; 
                default:
                    return '未知错误';                  
            }
        } 

        // 2. 验证格式 (是否是图片格式)
        //  创建 finfo 资源
        $info = finfo_open(FILEINFO_MIME_TYPE);
        //   将 finfo 资源 和 文件做比较
        $mime = finfo_file($info,$file['tmp_name']);
        //  比较是否合法
        $alllow = array('image/jpeg','image/png','image/gif');  // 允许的类别
        if(!in_array($mime,$alllow)){
            return '只能上传'.implode(',',$alllow).'格式'; 
        } 

        // 3. 验证图片大小
        $size = 123456789;
        if($file['size'] > $size){
            return '文件大小不能超过'.number_format(($size/1024),1).'k';
        }

        // 4. 验证是否http上传
        if(!is_uploaded_file($file['tmp_name']))
            return '文件不是HTTP POST 上传的<br>';

        return null;  // 灭有错误
    }


    if(!empty($_POST)){
       if($error = check($_FILES['face'])){
           echo $error;
       }else {
            // 文件上传  上传的文件保存到当天的文件夹中
            $foldername = date('Y-m-d');  // 文件夹名称
            $folderpath = "./uploads/{$foldername}";  // 文件夹路径

            if(!is_dir($folderpath)){
                mkdir($folderpath);
            }
            $filename = uniqid('',True).strrchr($_FILES['face']['name'],'.');  //重新定义唯一 文件名
            $filepath = "$folderpath/$filename";   // 文件路径
            if(move_uploaded_file($_FILES['face']['tmp_name'],$filepath)){
                echo "上传成功,路径是:{$foldername}/{$filename}";
            }else{
                echo '上传失败<br/>'; 
            }
       }
    }


    ?>

    <form action="" method="POST" enctype="multipart/form-data">
        <input type="file" name="face">
        <input type="submit" name="button" value="上传"> 
    </form>
  • 相关阅读:
    RUST实践.md
    redis.md
    opencvrust.md
    aws rds can't connect to mysql server on 'xx'
    Foundation ActionScript 3.0 With Flash CS3 And Flex
    Foundation Flash Applications for Mobile Devices
    Flash Mobile Developing Android and iOS Applications
    Flash Game Development by Example
    Actionscript 3.0 迁移指南
    在SWT中非UI线程控制界面
  • 原文地址:https://www.cnblogs.com/ericblog1992/p/12986381.html
Copyright © 2011-2022 走看看