【问题标题】:Make session work with Curl (ZF2)使用 Curl (ZF2) 使会话工作
【发布时间】:2013-06-14 07:55:49
【问题描述】:

我在 Zend Framework 2 应用程序中使用 REST。为了测试我的 REST 调用,我使用 Curl 发送 REST 请求,如下所示:

$client = new Http\Client();
$client->setAdapter(new Http\Client\Adapter\Curl());

$request = new Http\Request();
$request->setUri($url);
$request->setMethod($method);

$response = $client->dispatch($request);
$jsonString = $response->getContent();

一切正常,只是 Curl 请求似乎忽略了会话。我需要在我的休息请求处理中访问登录用户,例如使 Acl 工作。当我使用 AngularJS 发送 REST 请求时,会话实际上是有效的。以下是我设置会话的方式:

$storage = new SessionArrayStorage();
$manager = new SessionManager($config, $storage);
$session = new Session('surveylab', $manager);

如何将会话信息传递给 Curl,以便在 Curl 请求中访问会话?

【问题讨论】:

  • 我的经验告诉我,Web 服务不应该依赖会话数据。将它们视为普通方法:因此,使用 curl 时,您每次调用方法时都会发送例如电子邮件 &passwd。

标签: php rest session curl zend-framework2


【解决方案1】:

检查 cURL 选项:

CURLOPT_COOKIEFILE
CURLOPT_COOKIEJAR

查找它们的 cURL 用法示例:

curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");

【讨论】:

    【解决方案2】:

    将您的登录凭据作为帖子发送到您的登录 url,从结果中提取 cookie 并将它们与下一个请求一起发送。我不知道您的应用程序是否会随着时间的推移更新 cookie,但您应该在必要时更新它们。 一些示例代码:

    curl_setopt_array($ch, array(
        CURLOPT_URL => "http://your/url",
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER => array('Cookie: ' . $cookies . '"'),
        CURLOPT_HEADER => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_POST => count($postData),
        CURLOPT_POSTFIELDS => $post_string
    ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-21
      • 2011-11-22
      • 2013-06-22
      • 2015-03-31
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多