How to send Username/Password and a Cookie with stream_context_create

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sukrub
    New Member
    • Apr 2015
    • 2

    How to send Username/Password and a Cookie with stream_context_create

    I am trying to get the HTML code from a remote site, which creates different HTML output based on the cookie being sent.

    So I am trying to send username/password and a cookie with stream_context_ create() function.

    It works without the $cookie in the header, but the I get the wrong HTML.

    With the $cookie I get:
    Warning: file_get_conten ts(http://www.url.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in simple_html_dom .php on line 78

    I think I just do not know the syntax. Please help.

    Here is my code:

    Code:
    <?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;
    }
    ?>
  • sukrub
    New Member
    • Apr 2015
    • 2

    #2
    I have resolved the issue by changing the code as follows,

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

    Comment

    Working...