两种方式实现模拟登陆(PHP)
今天整理了模拟登陆的方法及一些常用的参数,这里整理下。
方法一,通过curl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | function send() { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,"www.iamjs.net/server.php");//模拟登陆URL curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);//以文件流形式返回设为1,输出到页面设为2 curl_setopt($ch, CURLOPT_POST, 1); //设置提交形式为POST curl_setopt($ch, CURLOPT_POSTFIELDS, "submit=1&user=小徐&pwd=123456");//POST数据 curl_setopt($ch,CURLOPT_REFERER," http://jwc.scnu.edu.cn");//header中Referer来源信息 curl_setopt($ch,CURLOPT_AUTOREFERER,1);//当根据Location:重定向时,自动设置header中的Referer:信息。 curl_setopt($ch,HEADER,1);//返回响应是否返回头信息 curl_setopt($ch,CURLOPT_NOBODY,1)//启用时将不对HTML中的BODY部分进行输出。 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch,CURLOPT_TIMEOUT,10);//设置cURL允许执行的最长秒数。 curl_setopt($ch,CURLOPT_COOKIE,"fruit=apple; colour=red");//设定HTTP请求中"Cookie: "部分的内容。多个cookie用分号分隔,分号后带一个空格 curl_setopt($ch,CURLOPT_COOKIEFILE,"file"); curl_setopt($ch,CURLOPT_COOKIEJAR,"file");//同CURLOPT_COOKIEFILE值相同 curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5");//设置头信息useragent curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: text/plain', 'Content-length: 100','X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8'));//设置HTTP头信息,包括可设ip $output = curl_exet($ch); $infos = curl_getinfo($ch);//返回针对该curl相关信息的数组 $error = curl_error($ch); curl_close($ch); } |
方法二:通过file_get_content(转载)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //post的第一种写法 function post1() { $data = "ms=BE&iso=BE&vat=0462569145&BtnSubmitVat=Verify";//参数 $opts = array('http' => array ( 'method'=>"POST", 'header'=>"Accept-language: en\r\n" . "Content-type: application/x-www-form-urlencoded\r\n". "Content-Length: " . strlen($data) . "\r\n", 'content' => $data ) ); //file_get_content第三个参数是资源类型,所以要先把数组转换成资源类型 //stream_context_create 第一个参数必须是二唯数组,第二个数组必须是一唯数组 $context = stream_context_create($opts); $content = file_get_contents('www.iamjs.net/server.php', false, $opts);//如果url地址有空格,就要使用urlencode() return $content; } //post的第二种写法 function post2() { $data = array( 'ms'=>'BE', 'iso'=>'BE', 'vat'=>'0462569145', 'BtnSubmitVat'=>'Verify', ); $options = array('http'=>array( 'method'=>"POST", 'header'=> "Accept-language: en\r\n". "Content-type: application/x-www-form-urlencoded\r\n", 'content'=>http_build_query($data)//http_build_query是把数组转换为字符传的形式.结果形式:ms=BE&iso=BE&vat=0462569145&BtnSubmitVat=Verify,版本为php5才有 )); $context = stream_context_create($options); $content = file_get_contents('www.iamjs.net/server.php', false, $context); return $content; } //get的做法: $content = file_get_contents('www.iamjs.net/server.php?ms=BE&iso=BE&vat=0462569145&BtnSubmitVat=Verify'); |
总的来说,更喜欢curl
校园网锐捷登陆现实获取IP信息失败怎么办? error while loading shared libraries: libiconv.so.2: cannot open (转载)