php使用http帖子获取页面

时间:2013-05-02 07:53:34

标签: php post file-get-contents

我必须从页面http://cbseresults.nic.in/class1211/cbse122012.htm获取考试结果 样本号为4623447。 他们正在使用http post发布表单数据。我写了下面的代码来发布数据。但它没有提供所需的结果。我发布了所需的cookie和发布变量。但我仍然没有得到输出。什么改变我应该为send_post函数做什么,以便它能正常工作。这就是我的代码

echo cbse12_data_extractor(4623447);
function cbse12_data_extractor($regNo) {
    $source_url = 'http://cbseresults.nic.in/class1211/cbse122012.asp';
    $post_vars = array('regno'=>$regNo);
    $cookies = array('_tb_pingSent'=>1);
   // $extraHeaders = array('Host'=>'http://cbseresults.nic.in');
    return send_post($source_url,$post_vars,$cookies);
}

function send_post( $url, $data ,$cookies='',$extraHeaders = '') //sends data     array(param=>val,...) to the page $url in post method and returns the reply string
{
    $post    = http_build_query( $data );
    $header =  "Accept-language: en\r\n".
            "Content-Type: application/x-www-form-urlencoded\r\n" . 
            "Content-Length: " . strlen( $post ) . 
            "\r\nUser-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n";

    if($extraHeaders) {
        foreach($extraHeaders as  $headerN  => $val) {
            $header = $header.$headerN.': '.$val."\r\n";
        }

    } 
    if($cookies) {
        $cookieArr = array();
        foreach($cookies as  $cookie  => $value) {
            array_push($cookieArr,$cookie.'='.$value);
        }
        $cookieStr = "Cookie: ".implode('; ',$cookieArr)."\r\n";
        $header = $header.$cookieStr;
    }
    $context = stream_context_create( array(
         "http" => array(
             "method" => "POST",
            "header" => $header,
            "content" => $post 
        ) 
    ) );
    //echo $header;
    $page    = file_get_contents( $url, false, $context );
    return $page;
    }

1 个答案:

答案 0 :(得分:2)

您可以使用POST'发送file_get_contents个数据。使用CURL执行此任务

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,your_parameters);       
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);