Login with curl and move to another page

前端 未结 3 1013
执笔经年
执笔经年 2020-12-20 13:46

I\'m trying to access one page in a website with CURL, however it needs to be logged in i tried the code to login and it was successful



        
3条回答
  •  太阳男子
    2020-12-20 14:04

    First define these function to get an associative array containing the url header and content (see http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl):

    /**
     * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
     * array containing the HTTP server response header fields and content.
     */
    function get_web_page( $url, $params, $is_post = true )
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_USERAGENT      => "Mozilla/4.0 (compatible;)", // i'm mozilla
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        );
    
        if($is_post) { //use POST
    
            $options[CURLOPT_POST] = 1;
            $options[CURLOPT_POSTFIELDS] = http_build_query($params);
    
        } else { //use GET
    
            $url = $url.'?'.http_build_query($params);
    
        }
    
        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );
    
        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }
    

    try this to load the 'http://www.example.com/buy' after login is successful.

    // after curl login setup
    $exec = curl_exec($curl_crack);
    if(preg_match("/^you are logged|logout|successfully logged$/i",$exec))
    {
        // close login CURL resource, and free up system resources
        curl_close($curl_crack);
    
        $params = array('product_id'=>'xxxx', qty=>10);
        $url = 'http://www.example.com/buy';
    
        //use above function to get the url content via POST params
        $result = get_web_page($url, $params, true);
    
        if($result['http_code'] == 200) {
            //echo the content
            echo $result['content'];
            die();
        }
    }
    

提交回复
热议问题