p3k / multipart
多部分编码库
0.2.0
2016-12-28 14:50 UTC
Requires
- php: >5.4.0
README
此库将构建一个适合在HTTP请求中使用的Multipart编码字符串。
用法
在 composer.json
中要求
"p3k/multipart": "*"
// Using composer... require('vendor/autoload.php'); // ...or requiring directly require('src/p3k/Multipart.php'); // Create a new Multipart object $multipart = new p3k\Multipart(); // Example POST data $params = [ 'category' => [ 'one', 'two' ], 'name' => 'test', 'nested' => [ 'foo' => [ 'bar1', 'bar2' ], 'bar' => 'foo' ] ]; // Add the params to the request $multipart->addArray($params); // You can add files too! $multipart->addFile('photo', '/tmp/example.jpg', 'image/jpeg'); // Set up curl $ch = curl_init('http://localhost:8000/server.php'); curl_setopt($ch, CURLOPT_POST, true); // Set the POSTFIELDS to the result of this object curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart->data()); // You'll also need to set the Content-Type header curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-type: ' . $multipart->contentType() )); curl_exec($ch);
背景
内置的cURL库在构建多部分请求时没有正确地编码数组值。例如,这个请求导致“Notice: Array to string conversion”并使参数的值为“Array”
$params = array( 'category' => [ 'one', 'two' ] ); $ch = curl_init('http://localhost:8000/server.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); curl_exec($ch);
查看PHP错误
此库可以用作cURL内置编码的替代品。
测试
您可以使用此项目中提供的PHP和Ruby服务器测试接收此有效负载。
运行PHP服务器
cd servers
php -S localhost:8000
这将运行内置的PHP网络服务器,监听端口8000。运行上面的示例代码,您将看到$_POST变量被请求填充。
运行Ruby服务器,确保您已执行 bundle install sinatra
,然后
cd servers
ruby server.rb
然后您可以将内容发布到 http://localhost:4567/upload
,您将看到发布的对象的JSON表示。