[英]Why does my php upload not work?
TL; DR:為什么無法重新上傳上傳的數據?
我正在嘗試將用戶上傳到我的文件的數據上傳到另一台服務器。 這意味着,我要發布我的帖子數據。
我想將一些數據上傳到upload.php
,然后應該將其發布到test.php
(僅輸出原始發布數據)。 並且由於節省了內存,我希望它能在不將整個帖子生成為字符串的情況下工作。 因此,我也不想使用curl。
test.php的
<?php
echo 'foo', file_get_contents('php://input'), 'bar';
upload.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
執行相同upload.php
,我只是得到foobar
(以及test.php
的http標頭),而不是上載的內容。
最后,我設法解決了這個錯誤 。 顯然,其他服務器(也是我的服務器)取決於http標頭Content-Length
。
正如您在我的答案中看到的那樣,我沒有發送(也不計算)此標頭。 因此,當我最終現在計算並發送Content-Length
標頭時,一切正常。 這是缺少的行:
$content_length = fstat($client_upload)['size'];
fwrite($server_upload, 'Content-Length: ' . $content_length . $NL);
重新上傳(將上傳的數據上傳到我的服務器)無效,因為只要在Content-Length
標頭中指定了正文,其他服務器就只讀取正文。 因為我沒有發送此標頭,所以它不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.