【问题标题】:Why does my php upload not work?为什么我的 php 上传不起作用?
【发布时间】:2018-05-14 21:00:39
【问题描述】:

TL;DR:为什么重新上传上传的数据不起作用?

我正在尝试将用户上传到我的文件的数据上传到另一台服务器。这意味着,我想发布我的帖子数据。

我想上传一些数据到upload.php,然后应该发布到test.php(它只是输出原始的发布数据)。而且由于节省了内存,我希望它可以在不将整个帖子生成为字符串的情况下工作。因此我也不想使用 curl。

test.php

<?php
echo 'foo', file_get_contents('php://input'), 'bar';

上传.php

<?php
//new line variable
$NL = "\r\n";

//open the posted data as a resource
$client_upload = fopen('php://input', 'r');
//open the connection to the other server
$server_upload = fsockopen('ssl://example.com', 443);

//write the http headers to the socket
fwrite($server_upload, 'POST /test.php HTTP/1.1' . $NL);
fwrite($server_upload, 'Host: example.com' . $NL);
fwrite($server_upload, 'Connection: close' . $NL);
//header/body divider
fwrite($server_upload, $NL);

//loop until client upload reached the end
while (!feof($client_upload)) {
    fwrite($server_upload, fread($client_upload, 1024));
}
//close the client upload resource - not needed anymore
fclose($client_upload);

//intitalize response variable
$response = '';
//loop until server upload reached the end
while (!feof($server_upload)) {
    $response .= fgets($server_upload, 1024);
}
//close the server upload resource - not needed anymore
fclose($server_upload);

//output the response
echo $response;

当我将{ "test": true }(来自 Fiddler)发布到test.php 文件时,它会输出foo{ "test": true }bar

现在,当我尝试对upload.php 执行相同操作时,我只得到foobar(以及来自test.php 的http 标头),但没有上传内容。

【问题讨论】:

    标签: php file-upload fwrite fsockopen


    【解决方案1】:

    最后我设法修复这个错误。显然,其他服务器(和我的)依赖于 http 标头 Content-Length

    正如您在我的回答中看到的,我没有发送(也没有计算)这个标头。因此,当我终于计算并发送 Content-Length 标头时,一切正常。这是缺少的行:

    $content_length = fstat($client_upload)['size'];
    fwrite($server_upload, 'Content-Length: ' . $content_length . $NL);
    

    重新上传(上传到我的服务器的数据)不起作用,因为只要在Content-Length 标头中指定了正文,其他服务器就会读取正文。因为我没有发送此标头,所以它不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 2012-10-07
      相关资源
      最近更新 更多