发送带有数组的HTTP帖子-PHP [英] Send HTTP Post with Array - PHP

查看:43
本文介绍了发送带有数组的HTTP帖子-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此功能:

I'm trying to use this nice function:

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命令,我的问题是我试图以数组形式发送post参数,就像这样

to send a POST command to a specific url, my problem is i'm trying to send the post paramters in a form of an array, something like this

login[username]: myusername
login[password]: mypassword,

但是我无法做到这一点,使用:

however i'm not able to do that, calling the function with :

            $login_post = array('login[username]' => $email,
                            'login[password]' => '');
        do_post_request(getHost($website['code']), $login_post);

总是以以下形式将数据发送到帖子:

always send the data to the post in the form:

username: myusername
password: mypassword

如何避免这种情况(不使用curl)?非常感谢.

How can I avoid this (without using curl)? Thanks a lot.

谢谢

耶希亚

推荐答案

也许可以吗?

<?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 );
?>

这篇关于发送带有数组的HTTP帖子-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆