gpt4 book ai didi

php - 在 PHP 中合并文件和发布数据

转载 作者:搜寻专家 更新时间:2023-10-31 21:46:52 25 4
gpt4 key购买 nike

在工作中,我一直在处理一些包含多个图像上传字段的复杂表单(Symphony 的发布页面)。我需要一种快速合并 $_FILES$_POST 的方法,不幸的是,您不能简单地将两者与 array_merge 合并,因为它们不遵循相同的结构。

基本上,如果您有 $_POST[a][b],它将是 $_FILES[a][*][b]。将 * 替换为 nametypetmp_nameerror 之一>尺寸

$_FILES 数组的内容作为标准:

array
'image-a' => array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
'image-b' => array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
'image' => array
'name' => array
'sub' => array
'c' => string '' (length=0)
'type' => array
'sub' => array
'c' => string '' (length=0)
'tmp_name' => array
'sub' => array
'c' => string '' (length=0)
'error' => array
'sub' => array
'c' => int 4
'size' => array
'sub' => array
'c' => int 0

以及与$_POST合并后的所需数组:

array
'MAX_FILE_SIZE' => string '5242880' (length=7)
'image-a' => array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
'image-b' => array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
'image' => array
'sub' => array
'c' => array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0

最佳答案

这是我想出的解决方案,调用 get_file_post_data 返回合并后的数组:

<?php

if (!empty($_POST)) {
header('content-type: text/plain');

function merge_file_post_data($type, $file, &$post) {
foreach ($file as $key => $value) {
if (!isset($post[$key])) $post[$key] = array();
if (is_array($value)) merge_file_post_data($type, $value, $post[$key]);
else $post[$key][$type] = $value;
}
}

function get_file_post_data() {
$files = array(
'name' => array(),
'type' => array(),
'tmp_name' => array(),
'error' => array(),
'size' => array()
);
$post = $_POST;

// Flip the first level with the second:
foreach ($_FILES as $key_a => $data_a) {
foreach ($data_a as $key_b => $data_b) {
$files[$key_b][$key_a] = $data_b;
}
}

// Merge and make the first level the deepest level:
foreach ($files as $type => $data) {
merge_file_post_data($type, $data, $post);
}

return $post;
}

var_dump(get_file_post_data());
}

else echo '
<form action="" method="post" enctype="multipart/form-data">
<input name="MAX_FILE_SIZE" type="hidden" value="5242880">
<div><label class="file">Image A <input name="image-a" type="file"></label></div>
<div><label class="file">Image B <input name="image-b" type="file"></label></div>
<div><label class="file">Image C <input name="image[sub][c]" type="file"></label></div>
<div><button type="submit">Send</button></div>
</form>
';

?>

关于php - 在 PHP 中合并文件和发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1371544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com