编程语言
首页 > 编程语言> > 使用PHP和fsockopen()将文件上传到Google Code Hosting

使用PHP和fsockopen()将文件上传到Google Code Hosting

作者:互联网

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).

标签:post,fsockopen,php
来源: https://codeday.me/bug/20191107/2002375.html