PHP用file_get_contents实现带cookie的POST功能

将POST数据及COOKIE数据以数组形式传入函数中即可成功发送!

经试验请求成功,彻底解决网上其它方法不能发送或只能发送一个cookie的问题。

 

function postRequest($url,$data,$cookie=null)

{

    if (is_array($data))

    {

       ksort($data);

       $data = http_build_query($data);

    }

    if(is_array($cookie))

    {

        $str = '';

        foreach ($cookie as $key => $value){

            $str .= $key.'='.$value.'; ';

        }

        $cookie = substr($str,0,-1);

     }

    $opts = array(

       'http'=>array(

       'method'=>"POST",

       'header'=>"Content-type: application/x-www-form-urlencoded\r\n".

                  "Content-length:".strlen($data)."\r\n" . 

                  "Cookie: ".$cookie."\r\n" . 

                  "\r\n",

       'content' => $data,

       )

    );

    $context = stream_context_create($opts);

    $ret = file_get_contents($url, false, $context);

    return $ret;

}

全文:http://hi.baidu.com/shshgm/item/b3f74b8854c0e854e63d199d

posted @ 2014-05-11 10:09  stma  阅读(2797)  评论(0)    收藏  举报