我正在尝试使用这个不错的功能:
function do_post_request($url, $data, $optional_headers = null) {
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
将POST命令发送到特定网址,我的问题是我正在尝试以数组的形式发送帖子参数,类似这样的
login[username]: myusername
login[password]: mypassword,
然而我无法做到这一点,用以下方法调用函数:
$login_post = array('login[username]' => $email,
'login[password]' => '');
do_post_request(getHost($website['code']), $login_post);
始终以以下格式将数据发送到帖子:
username: myusername
password: mypassword
如何避免这种情况(不使用卷曲)?非常感谢。
由于
叶海亚
答案 0 :(得分:3)
也许就是这样?
<?php
// Define POST data
$donnees = array(
'login' => 'test',
'password' => '******' );
function http_build_headers( $headers ) {
$headers_brut = '';
foreach( $headers as $name => $value ) {
$headers_brut .= $name . ': ' . $value . "\r\n";
}
return $headers_brut;
}
$content = http_build_query( $donnees );
// define headers
$headers = http_build_headers( array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Content-Length' => strlen( $content) ) );
// Define context
$options = array( 'http' => array( 'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0',
'method' => 'POST',
'content' => $content,
'header' => $headers ) );
// Create context
$contexte = stream_context_create( $options );
// Send request
$return = file_get_contents( 'http://www.exemple.com', false, $contexte );
?>
答案 1 :(得分:0)
$login_post = array(
'login' => array(
'username' => $email,
'password' => ''))
答案 2 :(得分:0)
$url = 'http://your_url.com/path';
$data = array('login' => 'usrnname', 'password' => '**');
$opt = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($opt);
$result = file_get_contents($url, false, $context);
var_dump($result);
此方法不使用curl。