如何在Lithium中为cURL提交POST

时间:2013-08-18 04:53:38

标签: php post curl lithium

我正在尝试为旧版API创建自定义Auth适配器。我们调用适配器TR42。现在,我正在调试TR42::check()所以我正在使用硬编码值:

<?php
class TR42 extends \lithium\core\Object {

    public function __construct(array $config = []) {
        $defaults = [
            'scheme' => 'http',
            'host' => 'localhost/tr42/mock_api_authenticate.php',
            'action' => 'authLookup',
            'fields' => ['username', 'password'],
            'method' => 'POST'
        ];
        parent::__construct($config + $defaults);
    }

    public function check($credentials, array $options = []) {
        $postConfig = [
            /**
             * Should I be using 'body' or 'query' to submit POST fields?
             */
            'body' => [
                'username' => 'housni',
                'password' => sha1('legacyHashedPassword'),
                'action' => 'authLookup'
            ],
            'query' => 'username=housni&password=' . sha1('legacyHashedPassword') . '&action=authLookup',
        ];
        $request = new Request($postConfig + $this->_config);

        $stream = new Curl($this->_config);
        $stream->open();
        $stream->write($request);
        $response = $stream->read();
        $stream->close();

        echo '<pre>' . print_r($response, true) . '</pre>';
        die();
    }
}
?>

文件http://localhost/tr42/mock_api_authenticate.php如下所示:

<?php
echo '<h1>This request is: ' . $_SERVER['REQUEST_METHOD'] . '</h1>';
if (!empty($_POST)) {
    echo '<h1>YAY</h1>';
} else {
    echo '<h1>NAY</h1>';
}

echo '<pre>' . print_r($_POST, true) . '</pre>';
?>

由于我的cURL代码提交了一个POST请求,我希望我的$ _POST可以在mock_api_authenticate.php中填充,但这不会发生,因为TR42 :: check()的print_r()的输出是:< / p>

HTTP/1.1 200 OK
Date: Sun, 18 Aug 2013 04:46:34 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.4.17-1~lucid+1
Vary: Accept-Encoding
Content-Length: 63
Connection: close
Content-Type: text/html

This request is: POST

NAY

Array
(
)

它说请求是POST但POST数组(最后一个空数组)是空的。

我做错了什么?

感谢阅读:)

1 个答案:

答案 0 :(得分:1)

我建议使用Lithium ConnectionsService类,以避免以这种方式编写curl请求。

将旧的api连接配置(主机,端口等)提取到名为“api”的连接或其他任何内容,然后在适配器的check()正文中写下如下内容:

public function check($credentials, array $options = []) {
    return Connections::get('api')->connection->post('/tr42/mock_api_authenticate.php', $credentials);
}