php上传文件处理

通过 PHP,把文件上传到服务器。

创建一个文件上传表单 index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body> <form action="upload_file.php" method="post" name="upform" enctype="multipart/form-data"> <label for="file">请选择文件:</label> <input type="file" name="upfile"/> <br /> <input type="submit" name="submit" value="上传" /> </form> </body> </html>

创建上传脚本 upload_file.php

<?php
header("Content-Type: text/html; charset=utf-8");
$uptypes=array(
    'image/jpg',
    'image/jpeg',
    'image/png',
    'image/pjpeg',
    'image/gif',
    'image/bmp',
    'image/x-png'
);

if(true) {
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //服务器和执行环境信息,访问页面使用的请求方法

        $files = $_FILES['upfile'];
    
        //检查文件大小
        if($files['size'] > 2097152){
            echo '上传文件不得大于2M';
            exit;
        }
    
        //检查上传文件类型
        $ftype = $files['type'];
        if(!in_array($ftype,$uptypes)){  
        //in_array 检查数组中是否存在某个值
    
            echo '上传文件不符合类型';
            exit;
        }
    
        //取得上传文件的信息
        $fname = $files['tmp_name'];
        $image_info = getimagesize($fname);

        //取得上传文件的扩展名
        $name = $files['name'];
        $str_name = pathinfo($name); 
        //pathinfo() 函数以数组的形式返回文件路径的信息
        //pathinfo() 返回一个关联数组包含有 path 的信息。
        //包括以下的数组元素:
            //[dirname]
            //[basename]
            //[extension]

        $extname = strtolower($str_name['extension']); //strtolower() 函数把字符串转换为小写

        //上传路径,upload_file.php文件同目录创建一个upimg文件夹
        $upload_dir = "upimg/";
    
        $file_name = "LOGO".".".$extname;
        $str_file = $upload_dir.$file_name;

        //创建上传的目录
        if(!file_exists($upload_dir)){
        //file_exists() 函数检查文件或目录是否存在
            mkdir($upload_dir);
        }
    
        if(!move_uploaded_file($files['tmp_name'],$str_file)){
        //move_uploaded_file() 函数将上传的文件移动到新位置;move_uploaded_file(file,newloc)
            echo "上传文件失败";
            exit;
        }

        echo "<font color='red'>已经成功上传文件,文件名为:</font> <font color='blue'>".$str_file."<br/>";
        echo "宽度:".$image_info[0];
        echo "长度:".$image_info[1];
        echo "<br> 大小:".$files['size']."bytes<br></font>";
        echo "图片预览:<br>";
        echo "<img src="".$str_file.""><br/>";
        echo "已经成功上传文件!5秒后返回...";
    }

$url = "index.html";
echo "<script>";
echo "setTimeout('func()','5000');";
echo "function func(){";
echo "window.location.href='$url'";
echo "}";
echo "</script>";
}
?>
原文地址:https://www.cnblogs.com/wowchky/p/3277763.html