首页 > 解决方案 > 在 PHP 中使用 cookie 发布

问题描述

我想用 PHP 发送一个 POST 请求。我需要在内容中配置两个 vars 。我还需要在标题中指定两个 cookie。

我尝试使用 stream_context_create 和 curl_init 没有成功。例如,这是我的 stream_context_create 代码:

    $url = "http://localhost/web/show_comments.php?id=$_GET[com_id]#";
    $data = array('body' => "$_GET[comment]", 'userId' => "$_GET[spoof_id]");

    $options = array(
      'http' => array(
            'header'  => array("Content-type: application/x-www-form-urlencoded",
                               "Cookie: user=luis",
                               "Cookie: password:1234"),
            'method'  => 'POST',
            'content' => http_build_query($data)
            )
    );
    var_dump(http_build_query($data));
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    var_dump($result);

com_id、spoof_id 和 comment 是在 GET 请求中捕获的参数。

谢谢!!

标签: phphtmlhttpcookies

解决方案


已解决:即使有两个 cookie,也只需配置一个。通过这种方式,解决方案是:

    $url = "http://localhost/web/show_comments.php?id=$_GET[com_id]#";
$data = array('body' => "$_GET[comment]", 'userId' => "$_GET[spoof_id]");

$options = array(
  'http' => array(
        'header'  => array("Content-type: application/x-www-form-urlencoded",
                           "Cookie: user=luis;password:1234"),
        'method'  => 'POST',
        'content' => http_build_query($data)
        )
);
var_dump(http_build_query($data));
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);

推荐阅读