在PHP中使用Cookie进行POST

问题描述:

I want to send a POST request with PHP. I need to configure in the content two vars . Also I need to specify two cookies in header.

I tried with stream_context_create and with curl_init without success. For example, here is my stream_context_create code:

    $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 and comment are parameters catched in a GET request.

Thanks!!

SOLVED: Even if there are two cookies, only one have to be configured. By this way, the solution is:

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