gpt4 book ai didi

php - 如何在 php 中使用 post 请求保留文件名和扩展名?

转载 作者:行者123 更新时间:2023-12-04 15:02:57 26 4
gpt4 key购买 nike

抱歉,如果标题措辞不好,但我对此很陌生,并且仍在学习中。我花了大约一个小时谷歌搜索但找不到答案,所以我想我会发布我的问题。我有一个带有 php 脚本的 Web 服务器,我正在尝试能够从上传文件的 powershell 发送发布请求,该文件将保存到 Web 服务器。这是我现在的脚本:

<?php
$file = date("Hism") . ".txt";
file_put_contents($file, file_get_contents("php://input"));
?>

这有效,但它始终将文件扩展名设置为 txt,将文件名设置为日期。我发现一些我不完全理解的关于 $_FILES["file"]["name"] 但替换了 date("Hism") 的东西。 ".txt"部分给出了错误:

PHP Notice:  Undefined index: file in /home/ubuntu/phpServer/i.php on line 2
PHP Notice: Trying to access array offset on value of type null in /home/ubuntu/phpServer/i.php on line 2
PHP Warning: file_put_contents(): Filename cannot be empty in /home/ubuntu/phpServer/i.php on line 3

如果重要的话,我用来发送发布请求的 PowerShell 脚本是:

iwr $ip/i.php -method POST -infile C:\test.txt

最佳答案

我看到这个答案有点含糊,所以这是完整的答案。对于你的 i.php

<?php

// Outputs the files variable array
// var_dump($_FILES);
if (empty($_FILES)) return '$_FILES is empty';

// Why file? and name? please note that if you perform var_dump($_FILES) as stated above you will get
// the array that makes up $_FILES request.
// Also note in our request: name=`"file`"; filename=`"test.txt`"" Try to change and then see what var_dump dispalys.
$fileName = $_FILES['file']['name'];

// Note that tmp files are saved elese where check using var_dump($_FILES)
$fileTmpName = $_FILES['file']['tmp_name'];

// Now move to the current directory where the script is running from
move_uploaded_file($fileTmpName, $fileName);
?>

该脚本应该处理文件扩展名和名称的保存。上述脚本的来源以及您的新脚本请查看:

现在让我们转到iwr。您正在使用 Invoke-WebRequest do help iwr 获取更多信息。现在这个问题已经回答了很多次,但这里是:(下面的来源)

$Uri = 'http://my-ip/Stackoverflow/i.php'
$fileBytes = [System.IO.File]::ReadAllBytes('c:\test.txt');
$fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);
$boundary = [System.Guid]::NewGuid().ToString();

$LF = "`r`n";

$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"file`"; filename=`"test.txt`"",
"Content-Type: application/octet-stream$LF",
$fileEnc,
"--$boundary--$LF"
) -join $LF

以上脚本代码来自powershell invoke-restmethod multipart/form-data我建议您也看看那个。

iwr -Uri $Uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines

请注意,我使用的是 iwr,上面提到的源代码使用的是 irm。您可以在 help iwrhelp irm 上阅读更多信息或访问 Invoke-WebRequest

关于php - 如何在 php 中使用 post 请求保留文件名和扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66662705/

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