PHP-将文件转换为二进制文件并使用HTTP POST发送
我将使用php转换一些文件,并将其作为HTTP POST请求的一部分发送。 我的代码中有一部分:PHP-将文件转换为二进制文件并使用HTTP POST发送,php,http,post,Php,Http,Post,我将使用php转换一些文件,并将其作为HTTP POST请求的一部分发送。 我的代码中有一部分: $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => "Content-type: " . $this->contentType."", 'conte
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: " . $this->contentType."",
'content' => "file=".$file
)
));
$data = file_get_contents($this->url, false, $context);
变量$file
必须是我要发送的文件的字节表示形式吗
这是用php发送文件而不使用表单的正确方法吗?你有什么线索吗
另外,使用PHP将文件转换为字节表示的方法是什么?您可能会发现使用CURL更容易,例如:
function curlPost($url,$file) {
$ch = curl_init();
if (!is_resource($ch)) return false;
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , 0 );
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 0 );
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt( $ch , CURLOPT_POST , 1 );
curl_setopt( $ch , CURLOPT_POSTFIELDS , '@' . $file );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_VERBOSE , 0 );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
其中,$url是您要发布到的位置,$file是您要发送的文件的路径。奇怪的是,我刚刚写了一篇文章,说明了相同的场景。(). 但为了让您开始,以下代码应该可以工作:
<?php
$context = stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=--foo\r\n",
"content" => "--foo\r\n"
. "Content-Disposition: form-data; name=\"myFile\"; filename=\"image.jpg\"\r\n"
. "Content-Type: image/jpeg\r\n\r\n"
. file_get_contents("image.jpg") . "\r\n"
. "--foo--"
)
));
$html = file_get_contents("http://example.com/upload.php", false, $context);
你能更具体一点吗?转换成二进制是什么意思?你有什么样的文件?在目前的情况下,我想发送xml文件,但我认为上面的代码可以用来发送任何类型的文件,我希望这样。转换为二进制-将文件转换为字节数组。您可以直接发送xml文件。卷曲很适合这个。好的,这是真的。但如果我的限制是我想做的php服务器没有安装curl扩展名,那该怎么办呢?最后,我使用curl发送包含数据的文件。它很容易安装和使用。谢谢大家提供线索。我使用了以下代码: