使用php从传入的http POST重命名文件

时间:2013-07-30 12:32:15

标签: php

我正在尝试通过http POST重命名我接受的文件。请参阅代码:

<?php
$xmlData = fopen('php://input' , 'rb');
while (!feof($xmlData)) { $xmlString .= fread($xmlData, 4096); }
fclose($xmlData);

file_put_contents('temp/message' . date('m-d-y') . '-' . time() . '.xml', $xmlString, FILE_APPEND);

$xml = new SimpleXMLElement($xmlString);

$id = trim($xml->MSG->ID);
$receiver = trim($xml->MSG->RECEIVER);
$message = trim($xml->MSG->MESSAGE);
$sender = trim($xml->MSG->SENDER);
$binary = trim($xml->MSG->BINARY);
$sent = trim($xml->MSG->SENT);

foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
  array_push($messageTitles, trim($lineItem->title));
}

header('HTTP/1.0 200 OK');
exit();

现在我对如何重命名这一点感到轻微失落?

1 个答案:

答案 0 :(得分:3)

您甚至不需要保存文件以处理XML树。因此,您可以处理文件并最后移动file_put_contents(...)

<?php
$xmlData = fopen('php://input' , 'rb');
while (!feof($xmlData)) { $xmlString .= fread($xmlData, 4096); }
fclose($xmlData);

$xml = new SimpleXMLElement($xmlString);

$id = trim($xml->MSG->ID);
$receiver = trim($xml->MSG->RECEIVER);
$message = trim($xml->MSG->MESSAGE);
$sender = trim($xml->MSG->SENDER);
$binary = trim($xml->MSG->BINARY);
$sent = trim($xml->MSG->SENT);

foreach ($xml->{'line-items'}->{'line-item'} as $lineItem) {
  array_push($messageTitles, trim($lineItem->title));
}

file_put_contents("temp/$receiver.xml", $xmlString, FILE_APPEND); // warning: security issue here

header('HTTP/1.0 200 OK');
exit();

请注意,您应该强制执行安全限制,以防止用户使用任意名称命名您的文件。