PHP实现简单文件上传系统

博客介绍了PHP文件上传系统,包含index.php实现HTML页面,让用户填写学号、姓名并限制上传文件不超20M;fileSystem.php处理上传逻辑。同时提到PHP文件上传需修改相关参数,如php.ini的运行时间、内存等配置,以及Apache或Nginx配置文件的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录结构如下,其中包含两个代码文件和一个uploads文件夹(用于存放上传的文件)在这里插入图片描述

index.php

该代码实现html页面,包括需要填写学号和姓名,上传文件大小不得超过20M

<form action="fileSystem.php" method="post" enctype="multipart/form-data">
	<h3 style="color: red">文件大小不要超过20M</h3><hr>
	请输入学号:<input type="text" name="num"><br>
	请输入姓名:<input type="text" name="username"><br>
	<input type="hidden" name="MAX_FILE_SIZE" value="25000000" />
	<input type="file" name="myPicture[]" size= "25" maxlength="100"><br><br>
	<input type="submit" value="提交">
</form>
fileSystem.php

该代码处理文件上传逻辑

<?php
    header("Content-type=text/html;charset=utf-8");
    if (empty($_POST)) {
        exit("提交的表单数据超过post_max_size的配置");
    }
    // 转存post提交的各个变量
    $num = $_POST['num'];
    $username = $_POST['username'];
    $arr = $_FILES['myPicture'];
    $file =array();
    for ($i=0; $i < count($arr['name']); $i++) { 
        $file[$i]['name'] = $arr['name'][$i];
        $file[$i]['type'] = $arr['type'][$i];
        $file[$i]['tmp_name'] = $arr['tmp_name'][$i];
        $file[$i]['error'] = $arr['error'][$i];
        $file[$i]['size'] = $arr['size'][$i];
    }

    for ($i=0; $i < count($file); $i++) { 
        switch ($file[$i]['error']) {
            default:
                echo "Failed upload";
            case 0:          
                $fileName = $file[$i]['name'];
                $fileTemp = $file[$i]['tmp_name'];
                // 文件名称合成:uploads目录下,学号+姓名+文件后缀
                // 其中文件后缀使用了php字符串处理的几个方法,主要是通过判断"."的位置获取后缀名
                $destination = "uploads/" . $num . $username . substr($file[$i]['name'], strpos($file[$i]['name'], ".")) ;
                move_uploaded_file($fileTemp, $destination);
                echo "Successful upload";
                break;
            case 1:
                echo "php.ini upload_max_filesize is to small";
                break;
            case 2:
                echo "upload file is to large";
                break;
            case 3:
                echo "only part is ok";
                break;
            case 4:
                echo "no charge file";
                break;
        } 
    }   
?>

需要注意的是,php文件上传有诸多控制,需要修改相关参数

  1. 源代码

    <input type="hidden" name="MAX_FILE_SIZE" value="25000000" />
    
  2. php相关配置文件 php.ini文件
    max_execution_time = 30,每个脚本运行的最长时间max_input_time = 60,每个脚本可以消耗的时间
    memory_limit = 128M,脚本运行最大消耗的内存,-1为无限制
    post_max_size = 8M,表单提交最大数据

  3. Apache或者Nginx相关配置文件
    Apahce目录下的httpd.conf文件添加LimitRequestBody 31457280 即30M=30*1024*1024
    Nginx目录下的nginx.conf文件添加client_max_body_size 30M;

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值