如何使用stream_context_create()发送用户名/密码和Cookie

时间:2015-04-12 03:54:16

标签: php cookies

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

所以我尝试使用stream_context_create()函数发送用户名/密码和cookie。

它在标题中没有$ 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;
}
?>

1 个答案:

答案 0 :(得分:1)

更改您的代码如下:

    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;
}