如何使用 stream_context_create() 发送 Username/Password 和一个 Cookie

How to send Username/Password and a Cookie using stream_context_create()

我正在尝试从远程站点获取 HTML 代码,该代码会根据发送的 cookie 创建不同的 HTML 输出。

所以我正在尝试发送 username/password 和一个带有 stream_context_create() 函数的 cookie。

header 中没有 $cookie 也能正常工作,但我弄错了 HTML。

使用 $cookie 我收到警告:

警告:file_get_contents(http://www.myURL.com) [function.file-get-contents]:无法打开流:HTTP 请求失败! HTTP/1.1 401 在第 78 行 simple_html_dom.php 中未经授权

我想,我只是不懂语法。请帮忙。

这是我的代码:

<?php
function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
{
    $usernamepw = "username:password";
    $cookie     = "skipPostLogin=1";
    $context = stream_context_create(array(
        'http' => array(
            'header'  => "Authorization: Basic " . base64_encode($usernamepw) . $cookie, 
            'timeout' => 60
        )
    ));
    $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
    $contents = file_get_contents($url, $use_include_path, $context, $offset);
    if (empty($contents))
    {
        return false;
    }
    $dom->load($contents, $lowercase, $stripRN);
    return $dom;
}
?>

按如下方式更改您的代码:

    function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT)
{
    $usernamepw = "username:password";
    $cookie     = "skipPostLogin=1";

    $headers = array(
        'Authorization: Basic ' . base64_encode($usernamepw),
        'Cookie: ' . $cookie
    );

    $context = stream_context_create(array(
        'http' => array(
            'header'  => $headers,
            'timeout' => 60
        )
    ));
    $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $defaultBRText);
    $contents = file_get_contents($url, $use_include_path, $context, $offset);
    if (empty($contents))
    {
        return false;
    }
    $dom->load($contents, $lowercase, $stripRN);
    return $dom;
}