您好,欢迎访问一九零五行业门户网

PHP的cURL库功能简介 抓取网页、POST数据及其他

无论是你想从从一个链接上取部分数据,或是取一个xml文件并把其导入数据库,那怕就是简单的获取网页内容,反应釜curl 是一个功能强大的php库。本文主要讲述如果使用这个php库。
启用 curl 设置
首先,我们得先要确定我们的php是否开启了这个库,你可以通过使用php_info()函数来得到这一信息。
<?php phpinfo(); ?>
如果你可以在网页上看到下面的输出,那么表示curl库已被开启。
如果你看到的话,那么你需要设置你的php并开启这个库。如果你是在windows平台下,那么非常简单,你需要改一改你的php.ini文件的设置,找到php_curl.dll,并取消前面的分号注释就行了。如下所示:
//取消下在的注释
extension=php_curl.dll
如果你是在linux下面,那么,google排名你需要重新编译你的php了,编辑时,你需要打开编译参数——在configure命令上加上“–with-curl” 参数。
一个小示例
如果一切就绪,下面是一个小例程:
<?php // 初始化一个 curl 对象 $curl = curl_init(); // 设置你需要抓取的url curl_setopt($curl, curlopt_url, 'http://jb51.net'); // 设置header curl_setopt($curl, curlopt_header, 1); // 设置curl 参数,要求结果保存到字符串中还是输出到屏幕上。 curl_setopt($curl, curlopt_returntransfer, 1); // 运行curl,请求网页 $data = curl_exec($curl); // 关闭url请求 curl_close($curl); // 显示获得的数据 var_dump($data);
如何post数据
上面是抓取网页的代码,下面则是向某个网页post数据。假设我们有一个处理表单的网址http://www.example.com/sendsms.php,其可以接受两个表单域,一个是电话号码,一个是短信内容。
<?php $phonenumber = '13912345678'; $message = 'this message was generated by curl and php'; $curlpost = 'pnumber=' . urlencode($phonenumber) . '&message=' . urlencode($message) . '&submit=send'; $ch = curl_init();chain link fencing curl_setopt($ch, curlopt_url, 'http://www.example.com/sendsms.php'); curl_setopt($ch, curlopt_header, 1); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_post, 1); curl_setopt($ch, curlopt_postfields, $curlpost); $data = curl_exec(); curl_close($ch); ?>
从上面的程序我们可以看到,使用curlopt_post设置http协议的post方法,而不是get方法,然后以curlopt_postfields设置post的数据。
关于代理服务器
下面是一个如何使用代理服务器的示例。请注意其中高亮的代码,代码很简单,我就不用多说了。
<?php $ch = curl_init(); curl_setopt($ch, curlopt_url, 'http://www.example.com'); curl_setopt($ch, curlopt_header, 1); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_httpproxytunnel, 1); curl_setopt($ch, curlopt_proxy, 'fakeproxy.com:1080'); curl_setopt($ch, curlopt_proxyuserpwd, 'user:password'); $data = curl_exec(); curl_close($ch); ?>
关于ssl和cookie
关于ssl也就是https协议,煤气发生炉你只需要把curlopt_url连接中的http://变成https://就可以了。当然,还有一个参数叫curlopt_ssl_verifyhost可以设置为验证站点。
关于cookie,你需要了解下面三个参数:
curlopt_cookie,在当面的会话中设置一个cookie
curlopt_cookiejar,当会话结束的时候保存一个cookie
curlopt_cookiefile,cookie的文件。
http服务器认证
最后,我们来看一看http服务器认证的情况。
<?php $ch = curl_init(); curl_setopt($ch, curlopt_url, 'http://www.example.com'); curl_setopt($ch, curlopt_returntransfer, 1); curl_setopt($ch, curlopt_httpauth, curlauth_basic); curl_setopt(curlopt_userpwd, '[username]:[password]') $data = curl_exec(); curl_close($ch); ?>
关于其它更多的内容,请参看相关的curl手册。
更多php的curl库功能简介 抓取网页、post数据及其他。
其它类似信息

推荐信息