php上传文件

$_FILES

作用:用来接收前端上传的文件,并且存储到服务器上。

前端

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="./upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="ccc">
        <input type="submit" name="ddd" value="上传">
</form>
</body>
</html>

后端文件:方法一

php 复制代码
<?php
    // 1) 获取到前端元素对象
    $fileObject = $_FILES["ccc"];  

	// 2) 获取文件名字
    $filename = $fileObject["name"];  # 获取文件名字
    echo $filename;

	// 3) 服务器拿到文件之后,是放到内存中,放到tmp_name键的值就是内存中的路径
	$file_tmpname = $_FILES["ccc"]["tmp_name"];

	// 4) 移动文件
    move_uploaded_file($file_tmpname, '/opt/lampp/htdocs/wh069/crm/demo2/'.$filename); 
?>

后端文件:方法二

php 复制代码
<?php

    // 1) 获取对象
    $fileObject = $_FILES["ccc"];  # 对象类型是一个数组

    // 2) 获取文件对象的属性
    $filename = $fileObject["name"];  # 获取文件名字
    $filesize = $$fileObject["size"]; # 获取文件大小
    $file_tmpname = $_FILES["ccc"]["tmp_name"]; # 获取上传文件在服务器中的临时文件名(系统默认的)

    // 3) 读文件
    $file_obj = fopen("$file_tmpname", 'r');
    $file_content = fread($file_obj, $filesize);
    fclose($file_obj);

    // 4) 写文件
    $fielpath = "/opt/lampp/htdocs/wh069/crm/demo2/".$filename;
    $file_obj = fopen($fielpath, 'w');
    fwrite($file_obj, $file_content);
    fclose($file_obj);
?>

后端文件:方法三

php 复制代码
<?php

    // 1) 获取对象
    $fileObject = $_FILES["ccc"];  # 对象类型是一个数组

    // 2) 获取文件对象的属性
    $filename = $fileObject["name"];  # 获取文件名字
    $filesize = $$fileObject["size"]; # 获取文件大小
    $file_tmpname = $_FILES["ccc"]["tmp_name"]; # 获取上传文件在服务器中的临时文件名(系统默认的)

    // 3) 获取内容
    $file_contnets = file_get_contents("$file_tmpname");

    // 4) 写文件
    $fielpath = "/opt/lampp/htdocs/wh069/crm/demo2/".$filename;
    file_put_contents($fielpath, $file_contnets);
?>
相关推荐
BingoGo2 小时前
PHP 和 Elasticsearch:给你的应用加个强力搜索引擎
后端·php
A码农先森3 小时前
PHP转Go系列 | PHP8 这些新函数让你眼前一亮
php
BingoGo1 天前
PHP 如何利用 Opcache 来实现保护源码
后端·php
BingoGo2 天前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1233 天前
web专题之php代审(二)
php
侃侃_天下3 天前
最终的信号类
开发语言·c++·算法
BingoGo3 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
echoarts3 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix3 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题3 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5