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

如何在php中使用post请求保留文件名和扩展名?,php,post,Php,Post,很抱歉,如果标题写得不好,但我对这个很陌生,还在学习。我花了大约一个小时在谷歌上搜索,找不到答案,所以我想我应该发布我的问题。我有一个web服务器,上面有一个php脚本,我试图从powershell发送一个post请求,上传一个文件,然后文件将保存到web服务器。以下是我现在的脚本: <?php $file = date("Hism") . ".txt"; file_put_contents($file, file_get_contents(&quo

很抱歉,如果标题写得不好,但我对这个很陌生,还在学习。我花了大约一个小时在谷歌上搜索,找不到答案,所以我想我应该发布我的问题。我有一个web服务器,上面有一个php脚本,我试图从powershell发送一个post请求,上传一个文件,然后文件将保存到web服务器。以下是我现在的脚本:

<?php
$file = date("Hism") . ".txt";
file_put_contents($file, file_get_contents("php://input"));
?>
如果有必要,我用来发送post请求的powershell脚本是:

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

抱歉,如果这是一个愚蠢的问题,我对php非常陌生。提前谢谢

我建议您打印出您的服务器正在接收的确切信息,这样您就可以正确地处理它了。例如,使用
var\u转储($\u文件)
调试$\u FILES变量的内容,并查看文件名的实际保存方式。

我发现答案有点模糊,所以这里是完整的答案。 对于您的
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 -Uri $Uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines

注意:我使用的是
iwr
,上面提到的源代码使用的是
irm
。您可以阅读有关
帮助iwr
帮助irm
的更多信息,或访问为什么不重复一下
日期('Hism')
给您的信息?以确保文件名不存在empty@a.mola
date('Hism')
只给出日期,例如,2021年3月16日星期二20:26:49给出了一个名为
20264903.txt的文件。当我尝试这样做时,它是有效的。像定义
$file='filename.txt'
一样定义
$file
并替换
文件获取内容('php://input“)
带有空字符串(“”)。仅出于测试原因,它返回
array(0){}
,这是朝着正确方向迈出的一步,但是您知道这个问题可能是什么/如何解决吗?我认为您的PowerShell命令只是向PHP文件发送一个POST请求,并将“-infle C:\test.txt”的内容作为此请求的主体发送。最后,请求主体将无法正确格式化,无法通过PHP变量访问数据。使用
文件获取内容(“php://input“”
将为您提供请求的简单正文。但是,您无法访问$\u POST或$\u文件上的任何内容,因为您发送的请求正文错误。您需要更改PowerShell命令,以便通过此PHP脚本正确上载文件。这可能会起作用。无论如何,使用
curl
可能是正确的选择:谢谢,这很有效!结果证明,该类型不是
“multipart/form data”
,但我尝试使用失眠,这很有效,然后我回到这里,powershell脚本工作了。帮个大忙!对不起,我知道我已经说过它已经修复了,但是出于某种原因,
$\u FILES[“file”][“name”]
只是
temp.txt
,你知道这是为什么/我如何修复它吗?谷歌刚刚提出了一系列不相关的问题。
$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
iwr -Uri $Uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines