CURL

什么时候会用到模拟请求:想要得到别人网站上的一些内容,比如获取图片,把一个图片的地址写进去就行了

$ch=curl_init();   //初始化句柄

curl_setopt($ch,CURLOPT_URL,"http://localhost/first_php/d/CURL/get_postdata.php");   //设置要请求的路径或是网址

curl_setopt($ch,CURLOPT_POST,1);                                 //设置请求为post方式

curl_setopt($ch,CUTLOPT_PORT,80);

curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");//设置浏览器,不让别人知道我用的是什么浏览器

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);      //设置post请求的参数

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);   //设置返回值(curl_exec())格式为字符串格式

curl_setopt($ch, CURLOPT_HEADER, 0);              //不让内容以数据流的格式输出。

//如果是1的话,则是以数据流的格式输出,输出内容如下所示:

//HTTP/1.1 100 Continue
//HTTP/1.1 200 OK
//Date: Wed, 19 Oct 2016 08:28:20 GMT
//Server: Apache
//X-Frame-Options: SAMEORIGIN
//X-Powered-By: PHP/5.6.19
//Content-Length: 24
//Content-Type: text/html; charset=UTF-8

$str=curl_exec($ch);//发送请求

curl_close($ch);//关闭请求

 

获取网页内容的方法有:file_get_contents,file,fopen,fsockopen,curl

 

 1 <?php
 2 //模拟post请求(参数是隐藏的)
 3 //get_postdata.php一般是在别人的网站上,这是一个远程请求,想得到别人网站上的一些内容,这就需要用到模拟请求
 4 //此网站返回的内容是(当前用户是:张三)
 5 //这个url必须写完整,否则无法访问
 6 //fsockopen属于底层的请求,而curl_setopt是把它给封装了一下,一般使用curl_setopt
 7 $data=array('username'=>'张三','password'=>123);
 8 $ch=curl_init();//初始化句柄
 9 curl_setopt($ch, CURLOPT_URL, "http://localhost/first_php/d/CURL/get_postdata.php");//设置要请求的路径
10 curl_setopt($ch, CURLOPT_POST, 1);                //设置请求为post请求
11 curl_setopt($ch, CURLOPT_PORT, 80);
12 curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
13 //设置浏览器,不让别人知道我用的是什么浏览器
14 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);      //设置post请求的参数
15 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);   //设置返回值(curl_exec())格式为字符串格式
16 curl_setopt($ch, CURLOPT_HEADER, 0);              //不让内容以数据流的格式输出。
17 //如果是1的话,则是以数据流的格式输出,输出内容如下所示:
18 //HTTP/1.1 100 Continue
19 //HTTP/1.1 200 OK
20 //Date: Wed, 19 Oct 2016 08:28:20 GMT
21 //Server: Apache
22 //X-Frame-Options: SAMEORIGIN
23 //X-Powered-By: PHP/5.6.19
24 //Content-Length: 24
25 //Content-Type: text/html; charset=UTF-8
26 //当前用户是:张三
27 $str=curl_exec($ch);//发送请求
28 curl_close($ch);//关闭请求
29 echo"<pre>";
30 echo $str;

 

posted on 2016-12-06 20:57  PHP博客园  阅读(148)  评论(0)    收藏  举报

导航