php curl的使用

在PHP开发中,有时候需要在内 部网中进行开发。对于数据收集项目,有时候服务器需要连接Internet网络来获取Internet网络上的信息。但是,如果公司是通过防火墙上网,一 般的file_get_post_content函数就不行了。当然,通过一些socket操作,直接向proxy写http请求也是可以的,但是比较麻烦。本文讨 论用CURL库的简单代理实现。


1. CURL库的安装
查Google可以发现很多关于CURL库安装的文档,但实际上,一般的Linux Installation都包含了CURL库。我们可以通过<? phpinfo() ?>检查php编译参数来获取是否安装CURL库的信息。
如下所示:
./configure’ ‘–host=i386-redhat-linux’ ‘–build=i386-redhat-linux’ ‘–target=i386-redhat-linux-gnu’ ‘–program-prefix=’ ‘–prefix=/usr’ ‘–exec-prefix=/usr’ ‘–bindir=/usr/bin’ ‘–sbindir=/usr/sbin’ ‘–sysconfdir=/etc’ ‘–datadir=/usr/share’ ‘–includedir=/usr/include’ ‘–libdir=/usr/lib’ ‘–libexecdir=/usr/libexec’ ‘–localstatedir=/var’ ‘–sharedstatedir=/usr/com’ ‘–mandir=/usr/share/man’ ‘–infodir=/usr/share/info’ ‘–cache-file=../config.cache’ ‘–with-config-file-path=/etc’ ‘–with-config-file-scan-dir=/etc/php.d’ ‘–enable-force-cgi-redirect’ ‘–disable-debug’ ‘–enable-pic’ ‘–disable-rpath’ ‘–enable-inline-optimization’ ‘–with-bz2’ ‘–with-db4=/usr’ ‘–with-curl‘ ‘–with-exec-dir=/usr/bin’ ‘–with-freetype-dir=/usr’ ‘–with-png-dir=/usr’ ‘–with-gd’ ‘–enable-gd-native-ttf’ ‘–without-gdbm’ ‘–with-gettext’ ‘–with-ncurses’ ‘–with-gmp’ ‘–with-iconv103f’ ‘–with-jpeg-dir=/usr’ ‘–with-openssl’ ‘–with-png’ ‘–with-pspell’ ‘–with-regex=system’ ‘–with-xml’ ‘–with-expat-dir=/usr’ ‘–with-dom=shared,/usr’ ‘–with-dom-xslt=/usr’ ‘–with-dom-exslt=/usr’ ‘–with-xmlrpc=shared’ ‘–with-pcre-regex=/usr’ ‘–with-zlib’ ‘–with-layout=GNU’ ‘–enable-bcmath’ ‘–enable-exif’ ‘–enable-ftp’ ‘–enable-magic-quotes’ ‘–enable-safe-mode’ ‘–enable-sockets’ ‘–enable-sysvsem’ ‘–enable-sysvshm’ ‘–enable-track-vars’ ‘–enable-trans-sid’ ‘–enable-yp’ ‘–enable-wddx’ ‘–with-pear=/usr/share/pear’ ‘–with-imap=shared’ ‘–with-imap-ssl’ ‘–with-kerberos’ ‘–with-ldap=shared’ ‘–with-mysql=shared,/usr’ ‘–with-pgsql=shared’ ‘–with-snmp=shared,/usr’ ‘–with-snmp=shared’ ‘–enable-ucd-snmp-hack’ ‘–with-unixODBC=shared,/usr’ ‘–enable-memory-limit’ ‘–enable-bcmath’ ‘–enable-shmop’ ‘–enable-calendar’ ‘–enable-dbx’ ‘–enable-dio’ ‘–enable-mcal’ ‘–enable-mbstring’ ‘–enable-mbstr-enc-trans’ ‘–enable-mbregex’ ‘–with-apxs2=/usr/sbin/apxs’

2. 使用CURL库访问代理服务器
<?
function curl_string ($url,$user_agent,$proxy){

$ch = curl_init();
curl_setopt ($ch, CURLOPT_PROXY, $proxy);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($ch, CURLOPT_COOKIEJAR, “c:\cookie.txt”);
curl_setopt ($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
$result = curl_exec ($ch);
curl_close($ch);
return $result;

}

$url_page = “http://www.google.com“;
$user_agent = “Mozilla/4.0”;
$proxy = “http://192.11.222.124:8000“;
$string = curl_string($url_page,$user_agent,$proxy);
echo $string;
?>

发表评论

邮箱地址不会被公开。 必填项已用*标注