簡體   English   中英

使用PHP和fsockopen()將文件上傳到Google Code Hosting

[英]Upload a file to Google Code Hosting with PHP and fsockopen()

Google Code Hosting可以遠程上傳文件。 我一直在嘗試用PHP編寫腳本,將文件上傳到我的帳戶。 這是腳本本身:

<?php

/* I censored a few details. */
$username = '***@gmail.com';
$password = '***';
$file = 'test.txt';
$project = '***';
$summary = 'test';

$uploadHost = "$project.googlecode.com";
$projectUri = '/files';
$authToken = base64_encode("$username:$password");

define('CRLF',"\r\n");

$boundary = "afdljgdfgjidofjgoidjfgoijdfogjsog9054uy54rhh";
$fileContents = quoted_printable_encode(file_get_contents($file));
$body = array();

/* Summary field is required. */
$body[] = '--' . $boundary . CRLF . 'Content-Disposition: form-data; name="summary"' . CRLF . 'Content-Length: 4' . CRLF . CRLF . 'test';

/* The actual file. */
$body[] = '--' . $boundary . CRLF . 'Content-Disposition: form-data; name="filename"; filename="' . $file . '"' . CRLF .'Content-Type: text/plain' . CRLF . 'Content-Length: ' . strlen($fileContents) . CRLF . 'Content-Type: application/octet-stream' . CRLF . CRLF . $fileContents;

/* The end. */
$body[] = '--' . $boundary . '--';

$bodyString = implode(CRLF, $body);
$bodyLength = strlen($bodyString);

$headers = "POST $projectUri
Host: $project.googlecode.com
Authorization: Basic $authToken
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: $bodyLength

";

$fp = fsockopen("ssl://$uploadHost", 443, $errno, $errstr);
if ($fp)
{
 fwrite($fp, $headers . $bodyString);
 $response = '';
 while (!feof($fp))
  $response .= fgets($fp, 1024);
 fclose($fp);
}

 /* For debugging. */
header('Content-Type: text/plain');
echo $headers.$bodyString;
echo CRLF . CRLF . CRLF . $response;

我面臨的問題是服務器響應“411 Length Required”。 但是,我的標題中有Content-Length。 那么,為什么這不起作用?

這是HTTP中的實際請求:

POST /files
Host: ***.googlecode.com
Authorization: Basic ***
Content-Type: multipart/form-data; boundary=afdljgdfgjidofjgoidjfgoijdfogjsog9054uy54rhh
Content-Length: 386

--afdljgdfgjidofjgoidjfgoijdfogjsog9054uy54rhh
Content-Disposition: form-data; name="summary"
Content-Length: 4

test
--afdljgdfgjidofjgoidjfgoijdfogjsog9054uy54rhh
Content-Disposition: form-data; name="filename"; filename="test.txt"
Content-Type: text/plain
Content-Length: 8
Content-Type: application/octet-stream

testtext
--afdljgdfgjidofjgoidjfgoijdfogjsog9054uy54rhh--

我不明白。

HTTP標准要求您指定要使用的HTTP協議版本。 在您的情況下,將標題更改為:

$headers = "POST $projectUri HTTP/1.0
Host: $project.googlecode.com
Authorization: Basic $authToken
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: $bodyLength

";

我認為Google假設您使用的是協議的舊版本(<1.0),如果您沒有指定它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM