Jiliuke

激流客

centos的软件安装大致可以分为两种类型: [centos]rpm文件安装,使用rpm指令 类似[ubuntu]deb文件安装,使用dpkg指令 [centos]yum安装 类似[ubuntu]apt-get安装 rpm命令 (一)查询系统装已经安装的软件信息 对于一个rpm包来说,都是有”-“和”.”构成的,基本上有以下几部分组成: * 包名 * 版本信息 * 发布版本号 * 运行平台,当出现noarch,代表的是软件可以平台兼容 1)查询系统中已经安装的软件 rpm -qa 2)查询一个已经安装的文件属于哪个软件包; rpm -qf 文件名的绝对路径 3)查询已安装软件包都安装到何处; 软件名定义是:rpm包去除平台信息和后缀后的信息 rpm -ql 软件名 4)查询一个已安装软件包的信息 rpm -qi 软件名 5)查看一下已安装软件的配置文件; rpm -qc 软件名 6)查看一个已经安装软件的文档安装位置: rpm -qd 软件名 7)查看一下已安装软件所依赖的软件包及文件; rpm -qR 软件名 (二)对于未安装的软件包信息查询 1)查看一个软件包的用途、版本等信息; rpm -qpi rpm文件 2)查看一件软件包所包含的文件; rpm -qpl rpm文件 3)查看软件包的文档所在的位置; rpm -qpd rpm文件 4)查看一个软件包的配置文件; rpm -qpc rpm文件 5)查看一个软件包的依赖关系 rpm -qpR rpm文件 (三)软件包的安装、升级、删除等 1)安装或者升级一个rpm包 rpm -ivh rpm文件【安装】 rpm -Uvh rpm文件【更新】 2)删除一个rpm 包 rpm -e 软件名 如何需要不管依赖问题,强制删除软件,在如上命令其后加上 –nodeps (四)签名导入 rpm –import 签名文件 rpm –import RPM-GPG-KEY yum命令 (一)yum基本概念 1)yum是什么 yum = Yellow dog Updater, Modified 主要功能是更方便的添加/删除/更新RPM包. 它能自动解决包的倚赖性问题. 它能便于管理大量系统的更新问题 2)yum的特点 可以同时配置多个资源库(Repository) 简洁的配置文件(/etc/yum.conf 自动解决增加或删除rpm包时遇到的倚赖性问题 使用方便 保持与RPM数据库的一致性 3)yum安装 CentOS自带(yum-.noarch.rpm) #rpm -ivh yum-.noarch.rpm 在第一次启用yum之前首先需要导入系统的RPM-GPG-KEY: (二)yum指令的使用 当第一次使用yum管理软件时,yum会自动下载所需要的headers放置在/var/cache/yum目录下; 1) rpm包的更新 #检查可以更新的软件包 yum check-update #更新所有的软件包 yum update #更新特定的软件包 yum update kernel #大规模的升级 yum upgrade 2) rpm包的安装和删除 #rpm包的安装和删除 yum install xxx【服务名】 yum remove xxx【服务名】 3) yum缓存的相关信息 #清楚缓存中rpm包文件 yum clean packages #清楚缓存中rpm的头文件 yum clean headers #清除缓存中旧的头文件 yum clean old headers #清除缓存中旧的rpm头文件和包文件 yum clean all 4)软件包信息查询 #列出资源库中所有可以安装或更新的rpm包 yum list #列出资源库中特定的可以安装或更新以及已经安装的rpm包 yum list firfox* N:可以在rpm包名中使用通配符,查询类似的rpm包 #列出资源库中所有可以更新的rpm包 yum list updates #列出已经安装的所有的rpm包 yum list installed #列出已经安装的但是不包含在资源库中的rpm包 yum list extras N:通过如网站下载安装的rpm包 #rpm包信息显示(info参数同list),列出资源库中所有可以安装或更新的rpm包的信息 yum info #列出资源库中特定的可以安装或更新以及已经安装的rpm包的信息 yum info firefox* N:可以在rpm包名中使用匹配符 #列出资源库中所有可以更新的rpm包的信息 yum info updates #列出已经安装的所有的rpm包的信息 yum info installed #列出已经安装的但是不包含在资源库中的rpm包的信息 yum info extras N:通过如网站下载安装的rpm包的信息 #搜索匹配特定字符的rpm包 yum search firofox #搜索包含特定文件的rpm包 yum provides firefox (三)yum软件源更新 http://mirrors.163.com/.help/centos.html

有些时候我们需要在服务器里设置一个脚本,让他一开机就自己启动。方法如下: cd /etc/init.d vi youshell.sh #将youshell.sh修改为你自己的脚本名 编写自己的脚本后保存退出。 在编写脚本的时候,请先加入以下注释 #add for chkconfig #chkconfig: 2345 70 30 #description: the description of the shell #关于脚本的简短描述 #processname: servicename #第一个进程名,后边设置自启动的时候会用到 说明: 2345是指脚本的运行级别,即在2345这4种模式下都可以运行,234都是文本界面,5就是图形界面X 70是指脚本将来的启动顺序号,如果别的程序的启动顺序号比70小(比如44、45),则脚本需要等这些程序都启动以后才启动。 30是指系统关闭时,脚本的停止顺序号。 给脚本添加上可执行权限: chmod +x youshell.sh 利用chkconfig命令将脚本设置为自启动 chkconfig –add servicename 这样你的脚本就可以在开机后自动运行了。 另外,在redhat里也可以使用这个方法来实现开机自启动。 chkconfig的使用方法 chkconfig(check config) 功能说明:检查,设置系统的各种服务。 语  法:chkconfig [–add][–del][–list][系统服务]或chkconfig[–level<等级代号>][系统服务][on/off/reset] 补充说明:这是RedHat公司遵循GPL规则所开发的程序,它可查询操作系统在每一个执行等级中会执行哪些系统服务,其中包括各类常驻服务。 参数:  –add 增加所指定的系统服务,让chkconfig指令得以管理它,并同时在系统启动的叙述文件内增加相关数据。  –del 删除所指定的系统服务,不再由chkconfig指令管理,并同时在系统启动的叙述文件内删除相关数据。  –level<等级代号> 指定读系统服务要在哪一个执行等级中开启或关毕 1:chkconfig 命令也可以用来激活和解除服务。chkconfig –list 命令显示系统服务列表,以及这些服务在运行级别0到6中已被启动(on)还是停止(off)。 chkconfig –list chkconfig –list httpd httpd 0:off 1:off 2:on 3:on 4:on 5:on 6:off 2:chkconfig 还能用来设置某一服务在某一指定的运行级别内被启动还是被停运。譬如,要在运行级别3、4、5中停运 nscd 服务,使用下面的命令: chkconfig –level 345 nscd off 3:由 xinetd 管理的服务会立即被 chkconfig 影响。譬如,如果 xinetd 在运行,finger 被禁用,那么执行了 chkconfig finger on 命令后,finger 就不必手工地重新启动 xinetd 来立即被启用。对其它服务的改变在使用 chkconfig 之后不会立即生效。必须使用service servicename start/stop/restart命令来重起服务 第二种方法 编辑 /etc/rc.d/rc.local文件 格式为 程序名 程序路径 例如 a.sh /home/a.sh

1.查看ip方法 ifconfig 2.查看端口占用情况的命令: lsof -i tcp:80

查看ftpselinux状态 getsebool -a|grep ftp setsebool selinux状态 1开启|0关闭

#uname -a # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue # 查看操作系统版本 # cat /proc/cpuinfo # 查看CPU信息 # hostname # 查看计算机名 # lspci -tv # 列出所有PCI设备 # lsusb -tv # 列出所有USB设备 # lsmod # 列出加载的内核模块 # env # 查看环境变量 资源 # free -m # 查看内存使用量和交换区使用量 # df -h # 查看各分区使用情况 # du -sh <目录名> # 查看指定目录的大小 # grep MemTotal /proc/meminfo # 查看内存总量 # grep MemFree /proc/meminfo # 查看空闲内存量 # uptime # 查看系统运行时间、用户数、负载 # cat /proc/loadavg # 查看系统负载 磁盘和分区 # mount | column -t # 查看挂接的分区状态 # fdisk -l # 查看所有分区 # swapon -s # 查看所有交换分区 # hdparm -i /dev/hda # 查看磁盘参数(仅适用于IDE设备) # dmesg | grep IDE # 查看启动时IDE设备检测状况 网络 # ifconfig # 查看所有网络接口的属性 # iptables -L # 查看防火墙设置 # route -n # 查看路由表 # netstat -lntp # 查看所有监听端口 # netstat -antp # 查看所有已经建立的连接 # netstat -s # 查看网络统计信息 进程 # ps -ef # 查看所有进程 # top # 实时显示进程状态 用户 # w # 查看活动用户 # id <用户名> # 查看指定用户信息 # last # 查看用户登录日志 # cut -d: -f1 /etc/passwd # 查看系统所有用户 # cut -d: -f1 /etc/group # 查看系统所有组 # crontab -l # 查看当前用户的计划任务 服务 # chkconfig –list # 列出所有系统服务 # chkconfig –list | grep on # 列出所有启动的系统服务 程序 # rpm -qa # 查看所有安装的软件包

如何能在命令行下通过指令打开2.xls,随之系统会调用默认的打开程序就好了。 方法: xdg-open filename format: xdg-open { file | URL } 通过命令格式可以看出可以打开文件及url地址。 example: xdg-open http://www.baidu.com #打开网址 xdg-open ~/Downloads/2.xls #打开文件 xdg-open ~ #打开用户主目录

首先你得知道几个命令: ifconfig 查看网卡信息的命令(网卡以eth0~ethN命名,看你网卡用的是哪个)。另外,它只在root用户下可能,一般普通用户不能用。 route -n 查看路由的命令。 cat /etc/resolv.conf 查看DNS,配置DNS可在这个文件配置 命令行里有三种修改IP方法,其中一种是临时的,重启后就没有了,在此不提了。只说两种永久生效的: 1,在命令行里,通过命令调出图形界面配置,比较直观,容易配置: 命令 setup 弹出图形界面,选择network configuration —-> 回车—–>两个选项,第一个是网卡,第二个是DNS,在此不多讲了。写太多了,最主要是很直观。 最后配置完了后,点TAB键或者上下左右键 选:OK—->save—>save&quit—>quit 2,命令行编写配置文件来实现,一般你的网卡是eth0. # vi /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE=eth0 #描述网卡对应的设备别名,例如ifcfg-eth0的文件中它为eth0 BOOTPROTO=static #设置网卡获得ip地址的方式,可能的选项为static,dhcp或bootp,分别对应静态指定的 ip地址,通过dhcp协议获得的ip地址,通过bootp协议获得的ip地址 BROADCAST=192.168.0.255 #对应的子网广播地址 HWADDR=00:07:E9:05:E8:B4 #对应的网卡物理地址 IPADDR=192.168.0.2 #如果设置网卡获得 ip地址的方式为静态指定,此字段就指定了网卡对应的ip地址 IPV6INIT=no IPV6_AUTOCONF=no NETMASK=255.255.255.0 #网卡对应的网络掩码 NETWORK=192.168.0.0 #网卡对应的网络地址 ONBOOT=yes #系统启动时是否设置此网络接口,设置为yes时,系统启动时激活此设备 修改对应网卡的网关的配置文件 vi /etc/sysconfig/network NETWORKING=yes(表示系统是否使用网络,一般设置为yes。如果设为no,则不能使用网络,而且很多系统服务程序将无法启动) HOSTNAME=localhost(设置本机的主机名,这里设置的主机名要和/etc/hosts中设置的主机名对应) GATEWAY=192.168.1.1(设置本机连接的网关的IP地址。)

curl 是使用URL语法的传送文件工具,支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。curl 支持SSL证书、HTTP POST、HTTP PUT 、FTP 上传,kerberos、基于HTT格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道和大量其他有用的技巧。详见参考手册 原来php默认并不进行此项功能的扩展,但还是有的,只是没有让它生效罢了。打开PHP安装目录,搜索以下三个文件 ssleay32.dll、libeay32.dll和 php_curl.dll,一一拷贝到系统目录下的system32文件夹下,修改php.ini文件,找到;extension= php_curl.dll行,去掉前面的;号,保存,重启服务器。在站点目录下建立一个PHP文件,内容如下 $ch = curl_init(“http://www.php.net”); curl_exec($ch); curl_close($ch); 预览如果能打开http://www.php.net的话说明就安装成功了。 至于linux及unix的安装可以要麻烦一些,得从http://curl.haxx.se/或其他网站上下载curl库 ____________________________________________________________ 以下关于此函数各项使用参数: bool curl_setopt (int ch, string option, mixed value) curl_setopt()函数将为一选项。option参数是你想个CURL会话设置要的设置,value是这个选项给定的值。 下列选项的值将被作为长整形使用(在option参数中指定):   * CURLOPT_INFILESIZE: 当你上传一个文件到远程站点,这个选项告诉PHP你上传文件的大小。 * CURLOPT_VERBOSE: 如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值。 * CURLOPT_HEADER: 如果你想把一个头包含在输出中,设置这个选项为一个非零值。 * CURLOPT_NOPROGRESS: 如果你不会PHP为CURL传输显示一个进程条,设置这个选项为一个非零值。注意:PHP自动设置这个选项为非零值,你应该仅仅为了调试的目的来改变这个选项。 * CURLOPT_NOBODY: 如果你不想在输出中包含body部分,设置这个选项为一个非零值。 * CURLOPT_FAILONERROR: 如果你想让PHP在发生错误(HTTP代码返回大于等于300)时,不显示,设置这个选项为一人非零值。默认行为是返回一个正常页,忽略代码。 * CURLOPT_UPLOAD: 如果你想让PHP为上传做准备,设置这个选项为一个非零值。 * CURLOPT_POST: 如果你想PHP去做一个正规的HTTP POST,设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型,多数被HTML表单使用。 * CURLOPT_FTPLISTONLY: 设置这个选项为非零值,PHP将列出FTP的目录名列表。 * CURLOPT_FTPAPPEND: 设置这个选项为一个非零值,PHP将应用远程文件代替覆盖它。 * CURLOPT_NETRC: 设置这个选项为一个非零值,PHP将在你的 ./netrc 文件中查找你要建立连接的远程站点的用户名及密码。 * CURLOPT_FOLLOWLOCATION: 设置这个选项为一个非零值(象 “Location: “)的头,服务器会把它当做HTTP头的一部分发送(注意这是递归的,PHP将发送形如 “Location: “的头)。 * CURLOPT_PUT: 设置这个选项为一个非零值去用HTTP上传一个文件。要上传这个文件必须设置CURLOPT_INFILE和CURLOPT_INFILESIZE选项. * CURLOPT_MUTE: 设置这个选项为一个非零值,PHP对于CURL函数将完全沉默。 * CURLOPT_TIMEOUT: 设置一个长整形数,作为最大延续多少秒。 * CURLOPT_LOW_SPEED_LIMIT: 设置一个长整形数,控制传送多少字节。 * CURLOPT_LOW_SPEED_TIME: 设置一个长整形数,控制多少秒传送CURLOPT_LOW_SPEED_LIMIT规定的字节数。 * CURLOPT_RESUME_FROM: 传递一个包含字节偏移地址的长整形参数,(你想转移到的开始表单)。 * CURLOPT_SSLVERSION: 传递一个包含SSL版本的长参数。默认PHP将被它自己努力的确定,在更多的安全中你必须手工设置。 * CURLOPT_TIMECONDITION: 传递一个长参数,指定怎么处理CURLOPT_TIMEVALUE参数。你可以设置这个参数为TIMECOND_IFMODSINCE 或 TIMECOND_ISUNMODSINCE。这仅用于HTTP。 * CURLOPT_TIMEVALUE: 传递一个从1970-1-1开始到现在的秒数。这个时间将被CURLOPT_TIMEVALUE选项作为指定值使用,或被默认TIMECOND_IFMODSINCE使用。 下列选项的值将被作为字符串:   * CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。 * CURLOPT_USERPWD: 传递一个形如[username]:[password]风格的字符串,作用PHP去连接。 * CURLOPT_PROXYUSERPWD: 传递一个形如[username]:[password] 格式的字符串去连接HTTP代理。 * CURLOPT_RANGE: 传递一个你想指定的范围。它应该是”X-Y”格式,X或Y是被除外的。HTTP传送同样支持几个间隔,用逗句来分隔(X-Y,N-M)。 * CURLOPT_POSTFIELDS: 传递一个作为HTTP “POST”操作的所有数据的字符串。 * CURLOPT_REFERER: 在HTTP请求中包含一个”referer”头的字符串。 * CURLOPT_USERAGENT: 在HTTP请求中包含一个”user-agent”头的字符串。 * CURLOPT_FTPPORT: 传递一个包含被ftp “POST”指令使用的IP地址。这个POST指令告诉远程服务器去连接我们指定的IP地址。这个字符串可以是一个IP地址,一个主机名,一个网络界面名 (在UNIX下),或是‘-’(使用系统默认IP地址)。 * CURLOPT_COOKIE: 传递一个包含HTTP cookie的头连接。 * CURLOPT_SSLCERT: 传递一个包含PEM格式证书的字符串。 * CURLOPT_SSLCERTPASSWD: 传递一个包含使用CURLOPT_SSLCERT证书必需的密码。 * CURLOPT_COOKIEFILE: 传递一个包含cookie数据的文件的名字的字符串。这个cookie文件可以是Netscape格式,或是堆存在文件中的HTTP风格的头。 * CURLOPT_CUSTOMREQUEST: 当进行HTTP请求时,传递一个字符被GET或HEAD使用。为进行DELETE或其它操作是有益的,更Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing or another, more obscure, HTTP request. 注意: 在确认你的服务器支持命令先不要去这样做。下列的选项要求一个文件描述(通过使用fopen()函数获得):  * CURLOPT_FILE: 这个文件将是你放置传送的输出文件,默认是STDOUT. * CURLOPT_INFILE: 这个文件是你传送过来的输入文件。 * CURLOPT_WRITEHEADER: 这个文件写有你输出的头部分。 * CURLOPT_STDERR: 这个文件写有错误而不是stderr。用来获取需要登录的页面的例子,当前做法是每次或许都登录一次,有需要的人再做改进了. 摘几个从别的网站扣过来的例子: 例一: $cookie_jar = tempnam(‘./tmp’,’cookie’); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL, ‘http://**’); curl_setopt($ch, CURLOPT_POST, 1); $request = ‘email_address=&password=&action=’; curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar); //把返回来的cookie信息保存在$cookie_jar文件中 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设定返回的数据是否自动显示 curl_setopt($ch, CURLOPT_HEADER, false); //设定是否显示头信息 curl_setopt($ch, CURLOPT_NOBODY, false);//设定是否输出页面内容 curl_exec($ch); curl_close($ch); //get data after login 例二: $ch2 = curl_init(); curl_setopt($ch2, CURLOPT_URL, ‘http://*****’); curl_setopt($ch2, CURLOPT_HEADER, false); curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch2, CURLOPT_COOKIEFILE, $cookie_jar); $orders = curl_exec($ch2); echo ”; echo strip_tags($orders); echo ”; curl_close($ch2); 实践证明很稳定:) 例三: set_time_limit(0); function _rand() { $length=26; $chars = “0123456789abcdefghijklmnopqrstuvwxyz”; $max = strlen($chars) – 1; mt_srand((double)microtime() * 1000000); $string = ”; for($i = 0; $i < $length; $i++) { $string .= $chars[mt_rand(0, $max)]; } return $string; } $HTTP_SESSION=_rand(); echo $HTTP_SESSION; $HTTP_Server=”www.baidu.com"; $HTTP_URL=”/“; $ch = curl_init(); curl_setopt ($ch,CURLOPT_URL,”http://“.$HTTP_Server.$HTTP_URL); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_USERAGENT,”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”); //curl_setopt($ch,CURLOPT_COOKIE,$HTTP_SESSION); $res = curl_exec($ch); curl_close ($ch); print_r($res); 刷论坛代码: 1、抓cookies程序: $URL=”http://www.yoururl.com/bbs/login.asp?action=chk"; //填入论坛的登陆页面地址 $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$URL); curl_setopt($ch,CURLOPT_REFERER,”http://www.hxfoods.com/bbs/login.asp"); //设置,访问页面的来源地址 curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,’username=→→敢死队→&password=168168’); //分析登陆页面,把用户名,密码分别对应起来 curl_setopt ($ch, CURLOPT_HEADER,true); //使能显示http头, curl_exec($ch); if (curl_errno($ch)) { print curl_error($ch); } else { curl_close($ch); } 2、刷楼了: set_time_limit(0); //设置程序执行时间无限制 $i=10000; //耍10000次 for($j=0;$j<$i;$j++) { $URL=”http://www.yoururl.com/bbs/savepost.asp"; //这个地址是回复表单里面action的url地址 $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$URL); curl_setopt($ch,CURLOPT_REFERER,”http://www.hxfoods.com/bbs/dispbbs.asp?boardid=14&replyid=672709&id=127437&page=1&skin=0&Star=53"); //设置来源地址,如果不设置,论坛服务器有可能有验证不允许回复 curl_setopt($ch,CURLOPT_COOKIESESSION,true); //能保存cookie curl_setopt($ch,CURLOPT_COOKIE,”DvForum=userid=24122&usercookies=0&userhidden=2&password=w0reu3g775VrY745&userclass=%96%7C&username=%A1%FA%A1%FA%B8%D2%CB%C0%B6%D3%A1%FA&StatUserID=2194783945 “); //这儿就是设置cookie了 curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_NOBODY,1); //不显示内容,因为有很多论坛回复后要自动跳转。 curl_setopt($ch,CURLOPT_POSTFIELDS,’Body=gfdfgdfgasdfgdfgdfgdfg& followup=672709&RootID=127437&star=58&TotalUseTable=Dv_bbs3& amp;UserName=→→敢死队→&signflag=1&total=65535’); //把你分析的回复表单的参数分别赋值 curl_setopt ($ch, CURLOPT_HEADER,true); curl_exec($ch); if (curl_errno($ch)) { print curl_error($ch); } else { curl_close($ch); } } curl_close — 关闭一个curl会话 curl_copy_handle — 拷贝一个curl连接资源的所有内容和参数 curl_errno — 返回一个包含当前会话错误信息的数字编号 curl_error — 返回一个包含当前会话错误信息的字符串 curl_exec — 执行一个curl会话 curl_getinfo — 获取一个curl连接资源句柄的信息 curl_init — 初始化一个curl会话 curl_multi_add_handle — 向curl批处理会话中添加单独的curl句柄资源 curl_multi_close — 关闭一个批处理句柄资源 curl_multi_exec — 解析一个curl批处理句柄 curl_multi_getcontent — 返回获取的输出的文本流 curl_multi_info_read — 获取当前解析的curl的相关传输信息 curl_multi_init — 初始化一个curl批处理句柄资源 curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源 curl_multi_select — Get all the sockets associated with the cURL extension, which can then be “selected” curl_setopt_array — 以数组的形式为一个curl设置会话参数 curl_setopt — 为一个curl设置会话参数 curl_version — 获取curl相关的版本信息 curl_init()函数的作用初始化一个curl会话,curl_init()函数唯一的一个参数是可选的,表示一个url地址。 curl_exec()函数的作用是执行一个curl会话,唯一的参数是curl_init()函数返回的句柄。 curl_close()函数的作用是关闭一个curl会话,唯一的参数是curl_init()函数返回的句柄。 $ch = curl_init(“http://www.baidu.com/"); curl_exec($ch); curl_close($ch); curl_version()函数的作用是获取curl相关的版本信息,curl_version()函数有一个参数,不清楚是做什么的 print_r(curl_version()) curl_getinfo()函数的作用是获取一个curl连接资源句柄的信息,curl_getinfo()函数有两个参数,第一个参数是curl的资源句柄,第二个参数是下面一些常量: $ch = curl_init(“http://www.baidu.com/"); print_r(curl_getinfo($ch)); 可选的常量包括: CURLINFO_EFFECTIVE_URL 最后一个有效的url地址 CURLINFO_HTTP_CODE 最后一个收到的HTTP代码 CURLINFO_FILETIME 远程获取文档的时间,如果无法获取,则返回值为“-1” CURLINFO_TOTAL_TIME 最后一次传输所消耗的时间 CURLINFO_NAMELOOKUP_TIME 名称解析所消耗的时间 CURLINFO_CONNECT_TIME 建立连接所消耗的时间 CURLINFO_PRETRANSFER_TIME 从建立连接到准备传输所使用的时间 CURLINFO_STARTTRANSFER_TIME 从建立连接到传输开始所使用的时间 CURLINFO_REDIRECT_TIME 在事务传输开始前重定向所使用的时间 CURLINFO_SIZE_UPLOAD 上传数据量的总值 CURLINFO_SIZE_DOWNLOAD下载数据量的总值 CURLINFO_SPEED_DOWNLOAD平均下载速度 CURLINFO_SPEED_UPLOAD平均上传速度 CURLINFO_HEADER_SIZE header部分的大小 CURLINFO_HEADER_OUT发送请求的字符串 CURLINFO_REQUEST_SIZE在HTTP请求中有问题的请求的大小 CURLINFO_SSL_VERIFYRESULT Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER CURLINFO_CONTENT_LENGTH_DOWNLOAD 从Content-Length: field中读取的下载内容长度 CURLINFO_CONTENT_LENGTH_UPLOAD上传内容大小的说明 CURLINFO_CONTENT_TYPE 下载内容的“Content-type”值,NULL表示服务器没有发送有效的“Content-Type: header” curl_setopt()函数的作用是为一个curl设置会话参数。curl_setopt_array()函数的作用是以数组的形式为一个curl设置会话参数。 $ch = curl_init(); $fp = fopen(“example_homepage.txt”, “w”); curl_setopt($ch, CURLOPT_FILE, $fp); $options = array( CURLOPT_URL => ‘http://www.baidu.com/’, CURLOPT_HEADER => false ); curl_setopt_array($ch, $options); curl_exec($ch); curl_close($ch); fclose($fp); 可设置的参数有: CURLOPT_AUTOREFERER 自动设置header中的referer信息 CURLOPT_BINARYTRANSFER 在启用CURLOPT_RETURNTRANSFER时候将获取数据返回 CURLOPT_COOKIESESSION 启用时curl会仅仅传递一个session cookie,忽略其他的cookie,默认状况下curl会将所有的cookie返回给服务端。session cookie是指那些用来判断服务器端的session是否有效而存在的cookie。 CURLOPT_CRLF 启用时将Unix的换行符转换成回车换行符。 CURLOPT_DNS_USE_GLOBAL_CACHE 启用时会启用一个全局的DNS缓存,此项为线程安全的,并且默认为true。 CURLOPT_FAILONERROR 显示HTTP状态码,默认行为是忽略编号小于等于400的HTTP信息 CURLOPT_FILETIME 启用时会尝试修改远程文档中的信息。结果信息会通过curl_getinfo()函数的CURLINFO_FILETIME选项返回。 CURLOPT_FOLLOWLOCATION(无法curl获取数据时,试试这个参数,参数值设为true;) 启用时会将服务器服务器返回的“Location:”放在header中递归的返回给服务器,使用CURLOPT_MAXREDIRS可以限定递归返回的数量。 CURLOPT_FORBID_REUSE 在完成交互以后强迫断开连接,不能重用。 CURLOPT_FRESH_CONNECT 强制获取一个新的连接,替代缓存中的连接。 CURLOPT_FTP_USE_EPRT TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only. Added in PHP 5.0.0. CURLOPT_FTP_USE_EPSV TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV. CURLOPT_FTPAPPEND TRUE to append to the remote file instead of overwriting it. CURLOPT_FTPASCII An alias of CURLOPT_TRANSFERTEXT. Use that instead. CURLOPT_FTPLISTONLY TRUE to only list the names of an FTP directory. CURLOPT_HEADER 启用时会将头文件的信息作为数据流输出。 CURLOPT_HTTPGET 启用时会设置HTTP的method为GET,因为GET是默认是,所以只在被修改的情况下使用。 CURLOPT_HTTPPROXYTUNNEL 启用时会通过HTTP代理来传输。 CURLOPT_MUTE 讲curl函数中所有修改过的参数恢复默认值。 CURLOPT_NETRC 在连接建立以后,访问/.netrc文件获取用户名和密码信息连接远程站点。 CURLOPT_NOBODY 启用时将不对HTML中的body部分进行输出。 CURLOPT_NOPROGRESS 启用时关闭curl传输的进度条,此项的默认设置为true CURLOPT_NOSIGNAL 启用时忽略所有的curl传递给php进行的信号。在SAPI多线程传输时此项被默认打开。 CURLOPT_POST 启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。 CURLOPT_PUT 启用时允许HTTP发送文件,必须同时设置CURLOPT_INFILE和CURLOPT_INFILESIZE CURLOPT_RETURNTRANSFER 讲curl_exec()获取的信息以文件流的形式返回,而不是直接输出。 CURLOPT_SSL_VERIFYPEER FALSE to stop cURL from verifying the peer’s certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10. CURLOPT_TRANSFERTEXT TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode. CURLOPT_UNRESTRICTED_AUTH 在使用CURLOPT_FOLLOWLOCATION产生的header中的多个locations中持续追加用户名和密码信息,即使域名已发生改变。 CURLOPT_UPLOAD 启用时允许文件传输 CURLOPT_VERBOSE 启用时会汇报所有的信息,存放在STDERR或指定的CURLOPT_STDERR中 CURLOPT_BUFFERSIZE 每次获取的数据中读入缓存的大小,这个值每次都会被填满。 CURLOPT_CLOSEPOLICY 不是CURLCLOSEPOLICY_LEAST_RECENTLY_USED就是CURLCLOSEPOLICY_OLDEST,还存在另外三个,但是curl暂时还不支持。. CURLOPT_CONNECTTIMEOUT 在发起连接前等待的时间,如果设置为0,则不等待。 CURLOPT_DNS_CACHE_TIMEOUT 设置在内存中保存DNS信息的时间,默认为120秒。 CURLOPT_FTPSSLAUTH The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). CURLOPT_HTTP_VERSION 设置curl使用的HTTP协议,CURL_HTTP_VERSION_NONE(让curl自己判断),CURL_HTTP_VERSION_1_0(HTTP/1.0),CURL_HTTP_VERSION_1_1(HTTP/1.1) CURLOPT_HTTPAUTH 使用的HTTP验证方法,可选的值 有:CURLAUTH_BASIC,CURLAUTH_DIGEST,CURLAUTH_GSSNEGOTIATE,CURLAUTH_NTLM,CURLAUTH_ANY,CURLAUTH_ANYSAFE, 可以使用“|”操作符分隔多个值,curl让服务器选择一个支持最好的值,CURLAUTH_ANY等价于CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM,CURLAUTH_ANYSAFE等价于CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM CURLOPT_INFILESIZE 设定上传文件的大小 CURLOPT_LOW_SPEED_LIMIT 当传输速度小于CURLOPT_LOW_SPEED_LIMIT时,PHP会根据CURLOPT_LOW_SPEED_TIME来判断是否因太慢而取消传输。 CURLOPT_LOW_SPEED_TIME The number of seconds the transfer should be below CURLOPT_LOW_SPEED_LIMIT for PHP to consider the transfer too slow and abort. 当传输速度小于CURLOPT_LOW_SPEED_LIMIT时,PHP会根据CURLOPT_LOW_SPEED_TIME来判断是否因太慢而取消传输。 CURLOPT_MAXCONNECTS 允许的最大连接数量,超过是会通过CURLOPT_CLOSEPOLICY决定应该停止哪些连接 CURLOPT_MAXREDIRS 指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的。 CURLOPT_PORT 一个可选的用来指定连接端口的量 CURLOPT_PROXYAUTH The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. CURLOPT_PROXYPORT The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY. CURLOPT_PROXYTYPE Either CURLPROXY_HTTP (default) or CURLPROXY_SOCKS5. CURLOPT_RESUME_FROM 在恢复传输时传递一个字节偏移量(用来断点续传) CURLOPT_SSL_VERIFYHOST 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided. CURLOPT_SSLVERSION The SSL version (2 or 3) to use. By default PHP will try to determine this itself, although in some cases this must be set manually. CURLOPT_TIMECONDITION 如果在CURLOPT_TIMEVALUE指定的某个时间以后被编辑过,则使用CURL_TIMECOND_IFMODSINCE返回页面,如果没有被修 改过,并且CURLOPT_HEADER为true,则返回一个”304 Not Modified”的header,CURLOPT_HEADER为false,则使用CURL_TIMECOND_ISUNMODSINCE,默认值为 CURL_TIMECOND_IFMODSINCE CURLOPT_TIMEOUT 设置curl允许执行的最长秒数 CURLOPT_TIMEVALUE 设置一个CURLOPT_TIMECONDITION使用的时间戳,在默认状态下使用的是CURL_TIMECOND_IFMODSINCE CURLOPT_CAINFO The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER. CURLOPT_CAPATH A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER. CURLOPT_COOKIE 设定HTTP请求中“Set-Cookie:”部分的内容。 CURLOPT_COOKIEFILE 包含cookie信息的文件名称,这个cookie文件可以是Netscape格式或者HTTP风格的header信息。 CURLOPT_COOKIEJAR 连接关闭以后,存放cookie信息的文件名称 CURLOPT_CUSTOMREQUEST A custom request method to use instead of “GET” or “HEAD” when doing a HTTP request. This is useful for doing “DELETE” or other, more obscure HTTP requests. Valid values are things like “GET”, “POST”, “CONNECT” and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering “GET /index.html HTTP/1.0rnrn” would be incorrect. Note: Don’t do this without making sure the server supports the custom request method first. CURLOPT_EGBSOCKET Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket. CURLOPT_ENCODING header中“Accept-Encoding: ”部分的内容,支持的编码格式为:”identity”,”deflate”,”gzip”。如果设置为空字符串,则表示支持所有的编码格式 CURLOPT_FTPPORT The value which will be used to get the IP address to use for the FTP “POST” instruction. The “POST” instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain ‘-’ to use the systems default IP address. CURLOPT_INTERFACE 在外部网络接口中使用的名称,可以是一个接口名,IP或者主机名。 CURLOPT_KRB4LEVEL KRB4(Kerberos 4)安全级别的设置,可以是一下几个值之一:”clear”,”safe”,”confidential”,”private”。默认的值 为”private”,设置为null的时候表示禁用KRB4,现在KRB4安全仅能在FTP传输中使用。 CURLOPT_POSTFIELDS 在HTTP中的“POST”操作。如果要传送一个文件,需要一个@开头的文件名 CURLOPT_PROXY 设置通过的HTTP代理服务器 CURLOPT_PROXYUSERPWD 连接到代理服务器的,格式为“[username]:[password]”的用户名和密码。 CURLOPT_RANDOM_FILE 设定存放SSL用到的随机数种子的文件名称 CURLOPT_RANGE 设置HTTP传输范围,可以用“X-Y”的形式设置一个传输区间,如果有多个HTTP传输,则使用逗号分隔多个值,形如:”X-Y,N-M”。 CURLOPT_REFERER 设置header中”Referer: ” 部分的值。 CURLOPT_SSL_CIPHER_LIST A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists. CURLOPT_SSLCERT 传递一个包含PEM格式证书的字符串。 CURLOPT_SSLCERTPASSWD 传递一个包含使用CURLOPT_SSLCERT证书必需的密码。 CURLOPT_SSLCERTTYPE The format of the certificate. Supported formats are “PEM” (default), “DER”, and “ENG”. CURLOPT_SSLENGINE The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY. CURLOPT_SSLENGINE_DEFAULT The identifier for the crypto engine used for asymmetric crypto operations. CURLOPT_SSLKEY The name of a file containing a private SSL key. CURLOPT_SSLKEYPASSWD The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY. Note: Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe. CURLOPT_SSLKEYTYPE The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are “PEM” (default), “DER”, and “ENG”. CURLOPT_URL 需要获取的URL地址,也可以在PHP的curl_init()函数中设置。 CURLOPT_USERAGENT 在HTTP请求中包含一个”user-agent”头的字符串。 CURLOPT_USERPWD 传递一个连接中需要的用户名和密码,格式为:“[username]:[password]”。 CURLOPT_HTTP200ALIASES 设置不再以error的形式来处理HTTP 200的响应,格式为一个数组。 CURLOPT_HTTPHEADER 设置一个header中传输内容的数组。 CURLOPT_POSTQUOTE An array of FTP commands to execute on the server after the FTP request has been performed. CURLOPT_QUOTE An array of FTP commands to execute on the server prior to the FTP request. CURLOPT_FILE 设置输出文件的位置,值是一个资源类型,默认为STDOUT (浏览器)。 CURLOPT_INFILE 在上传文件的时候需要读取的文件地址,值是一个资源类型。 CURLOPT_STDERR 设置一个错误输出地址,值是一个资源类型,取代默认的STDERR。 CURLOPT_WRITEHEADER 设置header部分内容的写入的文件地址,值是一个资源类型。 CURLOPT_HEADERFUNCTION 设置一个回调函数,这个函数有两个参数,第一个是curl的资源句柄,第二个是输出的header数据。header数据的输出必须依赖这个函数,返回已写入的数据大小。 CURLOPT_PASSWDFUNCTION 设置一个回调函数,有三个参数,第一个是curl的资源句柄,第二个是一个密码提示符,第三个参数是密码长度允许的最大值。返回密码的值。 CURLOPT_READFUNCTION 设置一个回调函数,有两个参数,第一个是curl的资源句柄,第二个是读取到的数据。数据读取必须依赖这个函数。返回读取数据的大小,比如0或者EOF。 CURLOPT_WRITEFUNCTION 设置一个回调函数,有两个参数,第一个是curl的资源句柄,第二个是写入的数据。数据写入必须依赖这个函数。返回精确的已写入数据的大小 curl_copy_handle()函数的作用是拷贝一个curl连接资源的所有内容和参数 $ch = curl_init(“http://www.baidu.com/”); $another = curl_copy_handle($ch); curl_exec($another); curl_close($another); curl_error()函数的作用是返回一个包含当前会话错误信息的字符串。 curl_errno()函数的作用是返回一个包含当前会话错误信息的数字编号。 curl_multi_init()函数的作用是初始化一个curl批处理句柄资源。 curl_multi_add_handle()函数的作用是向curl批处理会话中添加单独的curl句柄资源。curl_multi_add_handle()函数有两个参数,第一个参数表示一个curl批处理句柄资源,第二个参数表示一个单独的curl句柄资源。 curl_multi_exec()函数的作用是解析一个curl批处理句柄,curl_multi_exec()函数有两个参数,第一个参数表示一个批处理句柄资源,第二个参数是一个引用值的参数,表示剩余需要处理的单个的curl句柄资源数量。 curl_multi_remove_handle()函数表示移除curl批处理句柄资源中的某个句柄资源,curl_multi_remove_handle()函数有两个参数,第一个参数表示一个curl批处理句柄资源,第二个参数表示一个单独的curl句柄资源。 curl_multi_close()函数的作用是关闭一个批处理句柄资源。 $ch1 = curl_init(); $ch2 = curl_init(); curl_setopt($ch1, CURLOPT_URL, “http://www.baidu.com/”); curl_setopt($ch1, CURLOPT_HEADER, 0); curl_setopt($ch2, CURLOPT_URL, “http://www.google.com/”); curl_setopt($ch2, CURLOPT_HEADER, 0); $mh = curl_multi_init(); curl_multi_add_handle($mh,$ch1); curl_multi_add_handle($mh,$ch2); do { curl_multi_exec($mh,$flag); } while ($flag > 0); curl_multi_remove_handle($mh,$ch1); curl_multi_remove_handle($mh,$ch2); curl_multi_close($mh); curl_multi_getcontent()函数的作用是在设置了CURLOPT_RETURNTRANSFER的情况下,返回获取的输出的文本流。 curl_multi_info_read()函数的作用是获取当前解析的curl的相关传输信息。 curl_multi_select() Get all the sockets associated with the cURL extension, which can then be “selected” source url:http://www.hebaodans.com/2009/07/p-h-p-c-u-r-l-yong-fa/ HTTP request method PUT //a.php [php] view plaincopy bar ) echo json_encode($requestData); // Do something with data… } //curl.php [php] view plaincopy 1,’b’=>2); function doPut($url, $fields) { $fields = (is_array($fields)) ? http_build_query($fields) : $fields; if($ch = curl_init($url)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘PUT’); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Length: ‘ . strlen($fields))); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $rs=curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $rs; } else { return false; } } echo doPut(‘http://127.1/a.php',$array); 若是DELETE方法,则只需把PUT改为DELETE方法即可。 php curl class: [php] view plaincopy * $c = new curl; * // enable cache * $c = new curl(array(‘cache’=>true)); * // enable cookie * $c = new curl(array(‘cookie’=>true)); * // enable proxy * $c = new curl(array(‘proxy’=>true)); * * // HTTP GET Method * $html = $c->get(‘http://example.com'); * // HTTP POST Method * $html = $c->post(‘http://example.com/', array(‘q’=>’words’, ‘name’=>’moodle’)); * // HTTP PUT Method * $html = $c->put(‘http://example.com/', array(‘file’=>’/var/www/test.txt’); * * * @author Dongsheng Cai - https://github.com/dongsheng/cURL * @license http://www.gnu.org/copyleft/gpl.html GNU Public License / class curl { /** @var bool / public $cache = false; public $proxy = false; / @var array / public $response = array(); public $header = array(); /** @var string / public $info; public $error; / @var array / private $options; /** @var string / private $proxy_host = ‘’; private $proxy_auth = ‘’; private $proxy_type = ‘’; / @var bool / private $debug = false; private $cookie = false; /** * @param array $options */ public function __construct($options = array()){ if (!function_exists(‘curl_init’)) { $this->error = ‘cURL module must be enabled!’; trigger_error($this->error, E_USER_ERROR); return false; } // the options of curl should be init here. $this->resetopt(); if (!empty($options[‘debug’])) { $this->debug = true; } if(!empty($options[‘cookie’])) { if($options[‘cookie’] === true) { $this->cookie = ‘curl_cookie.txt’; } else { $this->cookie = $options[‘cookie’]; } } if (!empty($options[‘cache’])) { if (class_exists(‘curl_cache’)) { $this->cache = new curl_cache(); } } } /** * Resets the CURL options that have already been set */ public function resetopt(){ $this->options = array(); $this->options[‘CURLOPT_USERAGENT’] = ‘MoodleBot/1.0’; // True to include the header in the output $this->options[‘CURLOPT_HEADER’] = 0; // True to Exclude the body from the output $this->options[‘CURLOPT_NOBODY’] = 0; // TRUE to follow any “Location: “ header that the server // sends as part of the HTTP header (note this is recursive, // PHP will follow as many “Location: “ headers that it is sent, // unless CURLOPT_MAXREDIRS is set). //$this->options[‘CURLOPT_FOLLOWLOCATION’] = 1; $this->options[‘CURLOPT_MAXREDIRS’] = 10; $this->options[‘CURLOPT_ENCODING’] = ‘’; // TRUE to return the transfer as a string of the return // value of curl_exec() instead of outputting it out directly. $this->options[‘CURLOPT_RETURNTRANSFER’] = 1; $this->options[‘CURLOPT_BINARYTRANSFER’] = 0; $this->options[‘CURLOPT_SSL_VERIFYPEER’] = 0; $this->options[‘CURLOPT_SSL_VERIFYHOST’] = 2; $this->options[‘CURLOPT_CONNECTTIMEOUT’] = 30; } /** * Reset Cookie */ public function resetcookie() { if (!empty($this->cookie)) { if (is_file($this->cookie)) { $fp = fopen($this->cookie, ‘w’); if (!empty($fp)) { fwrite($fp, ‘’); fclose($fp); } } } } /** * Set curl options * * @param array $options If array is null, this function will * reset the options to default value. * */ public function setopt($options = array()) { if (is_array($options)) { foreach($options as $name => $val){ if (stripos($name, ‘CURLOPT_’) === false) { $name = strtoupper(‘CURLOPT_’.$name); } $this->options[$name] = $val; } } } /** * Reset http method * / public function cleanopt(){ unset($this->options[‘CURLOPT_HTTPGET’]); unset($this->options[‘CURLOPT_POST’]); unset($this->options[‘CURLOPT_POSTFIELDS’]); unset($this->options[‘CURLOPT_PUT’]); unset($this->options[‘CURLOPT_INFILE’]); unset($this->options[‘CURLOPT_INFILESIZE’]); unset($this->options[‘CURLOPT_CUSTOMREQUEST’]); } / * Set HTTP Request Header * * @param array $headers * / public function setHeader($header) { if (is_array($header)){ foreach ($header as $v) { $this->setHeader($v); } } else { $this->header[] = $header; } } /** * Set HTTP Response Header * / public function getResponse(){ return $this->response; } / * private callback function * Formatting HTTP Response Header * * @param mixed $ch Apparently not used * @param string $header * @return int The strlen of the header / private function formatHeader($ch, $header) { $this->count++; if (strlen($header) > 2) { list($key, $value) = explode(“ “, rtrim($header, “rn”), 2); $key = rtrim($key, ‘:’); if (!empty($this->response[$key])) { if (is_array($this->response[$key])){ $this->response[$key][] = $value; } else { $tmp = $this->response[$key]; $this->response[$key] = array(); $this->response[$key][] = $tmp; $this->response[$key][] = $value; } } else { $this->response[$key] = $value; } } return strlen($header); } /** * Set options for individual curl instance * * @param object $curl A curl handle * @param array $options * @return object The curl handle */ private function apply_opt($curl, $options) { // Clean up $this->cleanopt(); // set cookie if (!empty($this->cookie) || !empty($options[‘cookie’])) { $this->setopt(array(‘cookiejar’=>$this->cookie, ‘cookiefile’=>$this->cookie )); } // set proxy if (!empty($this->proxy) || !empty($options[‘proxy’])) { $this->setopt($this->proxy); } $this->setopt($options); // reset before set options curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,’formatHeader’)); // set headers if (empty($this->header)){ $this->setHeader(array( ‘User-Agent: MoodleBot/1.0’, ‘Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7’, ‘Connection: keep-alive’ )); } curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header); if ($this->debug){ echo ‘

Options

‘; var_dump($this->options); echo ‘

Header

‘; var_dump($this->header); } // set options foreach($this->options as $name => $val) { if (is_string($name)) { $name = constant(strtoupper($name)); } curl_setopt($curl, $name, $val); } return $curl; } /** * Download multiple files in parallel * * Calls {@link multi()} with specific download headers * * * $c = new curl; * $c->download(array( * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')), * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb')) * )); * * * @param array $requests An array of files to request * @param array $options An array of options to set * @return array An array of results / public function download($requests, $options = array()) { $options[‘CURLOPT_BINARYTRANSFER’] = 1; $options[‘RETURNTRANSFER’] = false; return $this->multi($requests, $options); } / * Mulit HTTP Requests * This function could run multi-requests in parallel. * * @param array $requests An array of files to request * @param array $options An array of options to set * @return array An array of results */ protected function multi($requests, $options = array()) { $count = count($requests); $handles = array(); $results = array(); $main = curl_multi_init(); for ($i = 0; $i < $count; $i++) { $url = $requests[$i]; foreach($url as $n=>$v){ $options[$n] = $url[$n]; } $handles[$i] = curl_init($url[‘url’]); $this->apply_opt($handles[$i], $options); curl_multi_add_handle($main, $handles[$i]); } $running = 0; do { curl_multi_exec($main, $running); } while($running > 0); for ($i = 0; $i < $count; $i++) { if (!empty($options[‘CURLOPT_RETURNTRANSFER’])) { $results[] = true; } else { $results[] = curl_multi_getcontent($handles[$i]); } curl_multi_remove_handle($main, $handles[$i]); } curl_multi_close($main); return $results; } /** * Single HTTP Request * * @param string $url The URL to request * @param array $options * @return bool */ protected function request($url, $options = array()){ // create curl instance $curl = curl_init($url); $options[‘url’] = $url; $this->apply_opt($curl, $options); if ($this->cache && $ret = $this->cache->get($this->options)) { return $ret; } else { $ret = curl_exec($curl); if ($this->cache) { $this->cache->set($this->options, $ret); } } $this->info = curl_getinfo($curl); $this->error = curl_error($curl); if ($this->debug){ echo ‘

Return Data

‘; var_dump($ret); echo ‘

Info

‘; var_dump($this->info); echo ‘

Error

‘; var_dump($this->error); } curl_close($curl); if (empty($this->error)){ return $ret; } else { return $this->error; // exception is not ajax friendly //throw new moodle_exception($this->error, ‘curl’); } } /** * HTTP HEAD method * * @see request() * * @param string $url * @param array $options * @return bool / public function head($url, $options = array()){ $options[‘CURLOPT_HTTPGET’] = 0; $options[‘CURLOPT_HEADER’] = 1; $options[‘CURLOPT_NOBODY’] = 1; return $this->request($url, $options); } /** * Recursive function formating an array in POST parameter * @param array $arraydata - the array that we are going to format and add into &$data array * @param string $currentdata - a row of the final postdata array at instant T * when finish, it’s assign to $data under this format: name[keyname][][]…[]=’value’ * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter */ function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) { foreach ($arraydata as $k=>$v) { $newcurrentdata = $currentdata; if (is_object($v)) { $v = (array) $v; } if (is_array($v)) { //the value is an array, call the function recursively $newcurrentdata = $newcurrentdata.’[‘.urlencode($k).’]‘; $this->format_array_postdata_for_curlcall($v, $newcurrentdata, $data); } else { //add the POST parameter to the $data array $data[] = $newcurrentdata.’[‘.urlencode($k).’]=’.urlencode($v); } } } /** * Transform a PHP array into POST parameter * (see the recursive function format_array_postdata_for_curlcall) * @param array $postdata * @return array containing all POST parameters (1 row = 1 POST parameter) / function format_postdata_for_curlcall($postdata) { if (is_object($postdata)) { $postdata = (array) $postdata; } $data = array(); foreach ($postdata as $k=>$v) { if (is_object($v)) { $v = (array) $v; } if (is_array($v)) { $currentdata = urlencode($k); $this->format_array_postdata_for_curlcall($v, $currentdata, $data); } else { $data[] = urlencode($k).’=’.urlencode($v); } } $convertedpostdata = implode(‘&’, $data); return $convertedpostdata; } / * HTTP POST method * * @param string $url * @param array|string $params * @param array $options * @return bool / public function post($url, $params = ‘’, $options = array()){ $options[‘CURLOPT_POST’] = 1; if (is_array($params)) { $params = $this->format_postdata_for_curlcall($params); } $options[‘CURLOPT_POSTFIELDS’] = $params; return $this->request($url, $options); } /** * HTTP GET method * * @param string $url * @param array $params * @param array $options * @return bool / public function get($url, $params = array(), $options = array()){ $options[‘CURLOPT_HTTPGET’] = 1; if (!empty($params)){ $url .= (stripos($url, ‘?’) !== false) ? ‘&’ : ‘?’; $url .= http_build_query($params, ‘’, ‘&’); } return $this->request($url, $options); } / * HTTP PUT method * * @param string $url * @param array $params * @param array $options * @return bool / public function put($url, $params = array(), $options = array()){ $file = $params[‘file’]; if (!is_file($file)){ return null; } $fp = fopen($file, ‘r’); $size = filesize($file); $options[‘CURLOPT_PUT’] = 1; $options[‘CURLOPT_INFILESIZE’] = $size; $options[‘CURLOPT_INFILE’] = $fp; if (!isset($this->options[‘CURLOPT_USERPWD’])){ $this->setopt(array(‘CURLOPT_USERPWD’=>’anonymous: noreply@moodle.org‘)); } $ret = $this->request($url, $options); fclose($fp); return $ret; } /** * HTTP DELETE method * * @param string $url * @param array $params * @param array $options * @return bool / public function delete($url, $param = array(), $options = array()){ $options[‘CURLOPT_CUSTOMREQUEST’] = ‘DELETE’; if (!isset($options[‘CURLOPT_USERPWD’])) { $options[‘CURLOPT_USERPWD’] = ‘anonymous: noreply@moodle.org‘; } $ret = $this->request($url, $options); return $ret; } / * HTTP TRACE method * * @param string $url * @param array $options * @return bool / public function trace($url, $options = array()){ $options[‘CURLOPT_CUSTOMREQUEST’] = ‘TRACE’; $ret = $this->request($url, $options); return $ret; } /** * HTTP OPTIONS method * * @param string $url * @param array $options * @return bool */ public function options($url, $options = array()){ $options[‘CURLOPT_CUSTOMREQUEST’] = ‘OPTIONS’; $ret = $this->request($url, $options); return $ret; } public function get_info() { return $this->info; } } /** * This class is used by cURL class, use case: * * * * $c = new curl(array('cache'=>true), 'module_cache'=>'repository'); * $ret = $c->get('http://www.google.com'); * * \ @package core * @subpackage file * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later / class curl_cache { /** @var string / public $dir = ‘’; / * * @param string @module which module is using curl_cache * / function __construct() { $this->dir = ‘/tmp/‘; if (!file_exists($this->dir)) { mkdir($this->dir, 0700, true); } $this->ttl = 1200; } /** * Get cached value * * @param mixed $param * @return bool|string / public function get($param){ $this->cleanup($this->ttl); $filename = ‘u_’.md5(serialize($param)); if(file_exists($this->dir.$filename)) { $lasttime = filemtime($this->dir.$filename); if(time()-$lasttime > $this->ttl) { return false; } else { $fp = fopen($this->dir.$filename, ‘r’); $size = filesize($this->dir.$filename); $content = fread($fp, $size); return unserialize($content); } } return false; } / * Set cache value * * @param mixed $param * @param mixed $val */ public function set($param, $val){ $filename = ‘u_‘.md5(serialize($param)); $fp = fopen($this->dir.$filename, ‘w’); fwrite($fp, serialize($val)); fclose($fp); } /** * Remove cache files * * @param int $expire The number os seconds before expiry */ public function cleanup($expire){ if($dir = opendir($this->dir)){ while (false !== ($file = readdir($dir))) { if(!is_dir($file) && $file != ‘.’ && $file != ‘..’) { $lasttime = @filemtime($this->dir.$file); if(time() - $lasttime > $expire){ @unlink($this->dir.$file); } } } } } /** * delete current user’s cache file * */ public function refresh(){ if($dir = opendir($this->dir)){ while (false !== ($file = readdir($dir))) { if(!is_dir($file) && $file != ‘.’ && $file != ‘..’) { if(strpos($file, ‘u_’)!==false){ @unlink($this->dir.$file); } } } } } } CURL是一个超强的命令行工具,其功能非常强大,有Linux/Unix版本的,也有Windows版本的,我平时就经常在Windows下面使用curl做一些测试,非常方便,有时用curl做测试比用浏览器做测试要快得多,方便得多。 1.curl命令帮助选项 C:>curl –help Usage: curl [options…] Options: (H) means HTTP/HTTPS only, (F) means FTP only -a/–append Append to target file when uploading (F) -A/–user-agent User-Agent to send to server (H) –anyauth Tell curl to choose authentication method (H) -b/–cookie Cookie string or file to read cookies from (H) –basic Enable HTTP Basic Authentication (H) -B/–use-ascii Use ASCII/text transfer -c/–cookie-jar Write cookies to this file after operation (H) -C/–continue-at Resumed transfer offset -d/–data HTTP POST data (H) –data-ascii HTTP POST ASCII data (H) –data-binary HTTP POST binary data (H) –negotiate Enable HTTP Negotiate Authentication (H) –digest Enable HTTP Digest Authentication (H) –disable-eprt Prevent curl from using EPRT or LPRT (F) –disable-epsv Prevent curl from using EPSV (F) -D/–dump-header Write the headers to this file –egd-file EGD socket path for random data (SSL) –tcp-nodelay Set the TCP_NODELAY option -e/–referer Referer URL (H) -E/–cert Client certificate file and password (SSL) –cert-type Certificate file type (DER/PEM/ENG) (SSL) –key Private key file name (SSL) –key-type Private key file type (DER/PEM/ENG) (SSL) –pass Pass phrase for the private key (SSL) –engine Crypto engine to use (SSL). “–engine list” for list –cacert CA certificate to verify peer against (SSL) –capath CA directory (made using c_rehash) to verify peer against (SSL) –ciphers SSL ciphers to use (SSL) –compressed Request compressed response (using deflate or gzip) –connect-timeout Maximum time allowed for connection –create-dirs Create necessary local directory hierarchy –crlf Convert LF to CRLF in upload -f/–fail Fail silently (no output at all) on errors (H) –ftp-create-dirs Create the remote dirs if not present (F) –ftp-pasv Use PASV instead of PORT (F) –ftp-ssl Enable SSL/TLS for the ftp transfer (F) -F/–form Specify HTTP multipart POST data (H) –form-string Specify HTTP multipart POST data (H) -g/–globoff Disable URL sequences and ranges using {} and [] -G/–get Send the -d data with a HTTP GET (H) -h/–help This help text -H/–header Custom header to pass to server (H) -i/–include Include protocol headers in the output (H/F) -I/–head Show document info only -j/–junk-session-cookies Ignore session cookies read from file (H) –interface Specify network interface to use –krb4 Enable krb4 with specified security level (F) -k/–insecure Allow curl to connect to SSL sites without certs (H) -K/–config Specify which config file to read -l/–list-only List only names of an FTP directory (F) –limit-rate Limit transfer speed to this rate -L/–location Follow Location: hints (H) –location-trusted Follow Location: and send authentication even to other hostnames (H) -m/–max-time Maximum time allowed for the transfer –max-redirs Maximum number of redirects allowed (H) –max-filesize Maximum file size to download (H/F) -M/–manual Display the full manual -n/–netrc Must read .netrc for user name and password –netrc-optional Use either .netrc or URL; overrides -n –ntlm Enable HTTP NTLM authentication (H) -N/–no-buffer Disable buffering of the output stream -o/–output Write output to instead of stdout -O/–remote-name Write output to a file named as the remote file -p/–proxytunnel Operate through a HTTP proxy tunnel (using CONNECT) –proxy-anyauth Let curl pick proxy authentication method (H) –proxy-basic Enable Basic authentication on the proxy (H) –proxy-digest Enable Digest authentication on the proxy (H) –proxy-ntlm Enable NTLM authentication on the proxy (H) -P/–ftp-port

Use PORT with address instead of PASV (F) -q If used as the first parameter disables .curlrc -Q/–quote Send command(s) to server before file transfer (F) -r/–range Retrieve a byte range from a HTTP/1.1 or FTP server –random-file File for reading random data from (SSL) -R/–remote-time Set the remote file’s time on the local output –retry Retry request times if transient problems occur –retry-delay When retrying, wait this many seconds between each –retry-max-time Retry only within this period -s/–silent Silent mode. Don’t output anything -S/–show-error Show error. With -s, make curl show errors when they occur –socks Use SOCKS5 proxy on given host + port –stderr Where to redirect stderr. - means stdout -t/–telnet-option Set telnet option –trace Write a debug trace to the given file –trace-ascii Like –trace but without the hex output -T/–upload-file Transfer to remote site –url Spet URL to work with -u/–user Set server user and password -U/–proxy-user Set proxy user and password -v/–verbose Make the operation more talkative -V/–version Show version number and quit -w/–write-out [format] What to output after completion -x/–proxy Use HTTP proxy on given port -X/–request Specify request command to use -y/–speed-time Time needed to trig speed-limit abort. Defaults to 30 -Y/–speed-limit Stop transfer if below speed-limit for ‘speed-time’ secs -z/–time-cond Transfer based on a time condition -0/–http1.0 Use HTTP 1.0 (H) -1/–tlsv1 Use TLSv1 (SSL) -2/–sslv2 Use SSLv2 (SSL) -3/–sslv3 Use SSLv3 (SSL) –3p-quote like -Q for the source URL for 3rd party transfer (F) –3p-url source URL to activate 3rd party transfer (F) –3p-user user and password for source 3rd party transfer (F) -4/–ipv4 Resolve name to IPv4 address -6/–ipv6 Resolve name to IPv6 address -#/–progress-bar Display transfer progress as a progress bar 2.查找页面源代码中的指定内容 例如查找京东商城首页含有js的代码 C:>curl www.360buy.com | find “js” % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 19 158k 19 31744 0 0 53531 0 0:00:03 –:–:– 0:00:03 65947 76 158k 76 121k 0 0 10763 0 0:00:15 0:00:11 0:00:04 7574 宿迁 99 158k 99 158k [南通](http://www.360buy.com/hel p/ziti/jiangsu.a
spx#jsnt) 100 158k 100 158k 0 0 12557 0 0:00:12 0:00:12 –:–:– 18859 </scrip t> document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga. js’ type=’text/javascript’%3E%3C/script%3E”)); 2.发送POST请求 a.传递一个参加时可以不用双引号 C:>curl -d action=get_basic_info http://localhost/1616.net/apps/contact/www/mobile.php [{“contact_id”:”3”,”last_update_time”:”1285832338”,”md5”:”7b682e0c3ed3b3bddb3219 a533477224”},{“contact_id”:”2”,”last_update_time”:”1286529929”,”md5”:”49ac542f51 19512682b72f1d44e6fe81”},{“contact_id”:”1”,”last_update_time”:”1285830870”,”md5” :”3926cb3b0320327c46430c6539d58e5e”}] b.传递多个参加时必须用双引号,否则会报错 C:>curl -d “action=edit&contact_id=2&name=testurl” http://localhost/1616.net/apps/contact/www/mobile.php 1 3.下载文件 比如下载百度首页的内容为baidu.html C:>curl -o baidu.html www.baidu.com % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 6218 100 6218 0 0 61564 0 –:–:– –:–:– –:–:– 173k 4.将网站产生的cookie内容写入到文件中 用curl -c cookie.txt www.baidu.com 产生的文件cookie.txt的内容如下: # Netscape HTTP Cookie File # http://www.netscape.com/newsref/std/cookie\_spec.html # This file was generated by libcurl! Edit at your own risk. .baidu.com TRUE / FALSE 2147483647 BAIDUID 3EC2799E83C7187A26CBBA67CCB71822:FG=1 5.测试域名绑定 输入命令 C:>curl -H “Host:www.baidu.com" http://202.108.22.5/ ip地址202.108.22.5是ping域名www.baidu.com以后返回的ip地址。 则返回百度首页所有的内容 如果随便输入一个域名www.abc.com,而ip地址不改变,则返回内容是空的,因为域名与ip地址不匹配了,这样就可以测试域名绑定是否正确了。 C:>curl -H “Host:www.abc.com" http://202.108.22.5/ curl: (52) Empty reply from server 查看更多http://www.blogkid.net/archives/2668.html 6.查看网站头信息 C:>curl -I www.baidu.com HTTP/1.1 200 OK Date: Fri, 08 Oct 2010 15:32:06 GMT Server: BWS/1.0 Content-Length: 6218 Content-Type: text/html;charset=gb2312 Cache-Control: private Expires: Fri, 08 Oct 2010 15:32:06 GMT Set-Cookie: BAIDUID=6E8167DF4E04A22A0659BBA1BE2905E7:FG=1; expires=Fri, 08-Oct-4 0 15:32:06 GMT; path=/; domain=.baidu.com P3P: CP=” OTI DSP COR IVA OUR IND COM “ Connection: Keep-Alive 7.查看URL跳转 C:>curl -L -I www.google.com HTTP/1.1 302 Found Location: http://www.google.com.hk/url?sa=p&hl=zh-CN&cki=PREF%3DID%3Dd0fa5e644a9 f891c:FF%3D2:LD%3Dzh-CN:NW%3D1:TM%3D1286551973:LM%3D1286551973:S%3DPQB5WhVsd17Bq 38k&q=http://www.google.com.hk/&ust=1286552003174649&usg=AFQjCNEwGJlI-YF0TG-6BiW ILw7U2qsr5Q Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: PREF=ID=d0fa5e644a9f891c:NW=1:TM=1286551973:LM=1286551973:S=oAe_1PXO MrFd73Jy; expires=Sun, 07-Oct-2012 15:32:53 GMT; path=/; domain=.google.com Set-Cookie: NID=39=C_aIB4kMtsJnMR5kwJKF9XAhB9_sEKTp5Qe-Y6Zcu7nNVrrBmKrr-687Zhf_r -wVNniv4kbb8BRCBR52EN2HdxaL2lGCBxUlEWjkGdZctAqdjyzZbwTb2Hh05UgYMTIO; expires=Sat , 09-Apr-2011 15:32:53 GMT; path=/; domain=.google.com; HttpOnly Date: Fri, 08 Oct 2010 15:32:53 GMT Server: gws Content-Length: 458 X-XSS-Protection: 1; mode=block HTTP/1.1 302 Found Location: http://www.google.com.hk/ Cache-Control: private Content-Type: text/html; charset=UTF-8 Set-Cookie: PREF=ID=d0fa5e644a9f891c:FF=2:LD=zh-CN:NW=1:TM=1286551973:LM=1286551 973:S=PQB5WhVsd17Bq38k; expires=Sun, 07-Oct-2012 15:32:53 GMT; path=/; domain=.g oogle.com.hk Date: Fri, 08 Oct 2010 15:32:53 GMT Server: gws Content-Length: 222 X-XSS-Protection: 1; mode=block HTTP/1.1 200 OK Date: Fri, 08 Oct 2010 15:32:53 GMT Expires: -1 Cache-Control: private, max-age=0 Content-Type: text/html; charset=Big5 Set-Cookie: PREF=ID=3f9f2340941ea76f:NW=1:TM=1286551973:LM=1286551973:S=m9wrFWJe Jbk4aFK2; expires=Sun, 07-Oct-2012 15:32:53 GMT; path=/; domain=.google.com.hk Set-Cookie: NID=39=Mlebw-qjMEK1ABTu-W1YWoQ-Tk27–cOtwLLrDWhmU8y0fqwgeyNz06XBZsYG 9yNwSCO_Ryzzt7q1GUXHgrM2jijr9vmLsW9ZXT2k6pve8f-IrdMyLJok4lRImiskdLR; expires=Sat , 09-Apr-2011 15:32:53 GMT; path=/; domain=.google.com.hk; HttpOnly Server: gws X-XSS-Protection: 1; mode=block Transfer-Encoding: chunked curl: (18) transfer closed with outstanding read data remaining 延伸阅读: http://blog.chinaunix.net/u/5591/showart.php?id=1957520 http://www.blogkid.net/archives/2668.html http://www.baidu.com/s?wd=curl http://www.google.com/search?hl=en&source=hp&q=curl http://blog.s135.com/post/389/ ============================================== 补充知识: 可以看作命令行浏览器 1、开启gzip请求 curl -I http://www.sina.com.cn/ -H Accept-Encoding:gzip,defalte 2、监控网页的响应时间 curl -o /dev/null -s -w “time_connect: %{time_connect}ntime_starttransfer: %{time_starttransfer}ntime_total: %{time_total}n” “http://www.kklinux.com" 3. 监控站点可用性 curl -o /dev/null -s -w %{http_code} “http://www.kklinux.com" 4、以http1.0协议请求(默认为http1.1) curl -0 ………….. 1)读取网页   $ curl linuxidc.com”>http://www.linuxidc.com   2)保存网页   $ curl http://www.linuxidc.com > page.html $ curl -o page.html http://www.linuxidc.com   3)使用的proxy服务器及其端口:-x   $ curl -x 123.45.67.89:1080 -o page.html http://www.linuxidc.com   4)使用cookie来记录session信息   $ curl -x 123.45.67.89:1080 -o page.html -D cookie0001.txt http://www.linuxidc.com option: -D 是把http的response里面的cookie信息存到一个特别的文件中去,这样,当页面被存到page.html的同时,cookie信息也被存到了cookie0001.txt里面了 5)那么,下一次访问的时候,如何继续使用上次留下的cookie信息呢?   使用option来把上次的cookie信息追加到http request里面去:-b   $ curl -x 123.45.67.89:1080 -o page1.html -D cookie0002.txt -b cookie0001.txt http://www.linuxidc.com 6)浏览器信息~~~~ 随意指定自己这次访问所宣称的自己的浏览器信息: -A curl -A “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” -x 123.45.67.89:1080 -o page.html -D cookie0001.txt http://www.yahoo.com 这样,服务器端接到访问的要求,会认为你是一个运行在Windows 2000上的IE6.0,嘿嘿嘿,其实也许你用的是苹果机呢! 而”Mozilla/4.73 [en] (X11; U; Linux 2.2; 15 i686”则可以告诉对方你是一台PC上跑着的Linux,用的是Netscape 4.73,呵呵呵 7) 另外一个服务器端常用的限制方法,就是检查http访问的referer。比如你先访问首页,再访问里面所指定的下载页,这第二次访问的referer地址就是第一次访问成功后的页面地 址。这样,服务器端只要发现对下载页面某次访问的referer地址不 是首页的地址,就可以断定那是个盗连了~~~~~ 讨厌讨厌~~~我就是要盗连~~~~~!! 幸好curl给我们提供了设定referer的option: -e curl -A “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” -x 123.45.67.89:1080 -e “mail.yahoo.com” -o page.html -D cookie0001.txt http://www.yahoo.com 这样,就可以骗对方的服务器,你是从mail.yahoo.com点击某个链接过来的了,呵呵呵 8)curl 下载文件 刚才讲过了,下载页面到一个文件里,可以使用 -o ,下载文件也是一样。 比如, curl -o 1.jpg http://cgi2.tky.3web.ne.jp/~zzh/screen1.JPG 这里教大家一个新的option: -O 大写的O,这么用: curl -O http://cgi2.tky.3web.ne.jp/~zzh/screen1.JPG 这样,就可以按照服务器上的文件名,自动存在本地了! 再来一个更好用的。 如果screen1.JPG以外还有screen2.JPG、screen3.JPG、….、screen10.JPG需要下载,难不成还要让我们写一个script来完成这些操作? 不干! 在curl里面,这么写就可以了: curl -O http://cgi2.tky.3web.ne.jp/~zzh/screen\[1-10\].JPG 呵呵呵,厉害吧?!~~~ 9) 再来,我们继续讲解下载! curl -O http://cgi2.tky.3web.ne.jp/~{zzh,nick}/\[001-201\].JPG 这样产生的下载,就是 zzh/001.JPG ~zzh/002.JPG … ~zzh/201.JPG ~nick/001.JPG ~nick/002.JPG … ~nick/201.JPG 够方便的了吧?哈哈哈 咦?高兴得太早了。 由于zzh/nick下的文件名都是001,002…,201,下载下来的文件重名,后面的把前面的文件都给覆盖掉了~~~ 没关系,我们还有更狠的! curl -o #2_#1.jpg http://cgi2.tky.3web.ne.jp/{zzh,nick}/[001-201].JPG –这是…..自定义文件名的下载? –对头,呵呵! #1是变量,指的是{zzh,nick}这部分,第一次取值zzh,第二次取值nick #2代表的变量,则是第二段可变部分—[001-201],取值从001逐一加到201 这样,自定义出来下载下来的文件名,就变成了这样: 原来: zzh/001.JPG —> 下载后: 001-zzh.JPG 原来: ~nick/001.JPG —> 下载后: 001-nick.JPG 这样一来,就不怕文件重名啦,呵呵 9) 继续讲下载 我们平时在windows平台上,flashget这样的工具可以帮我们分块并行下载,还可以断线续传。 curl在这些方面也不输给谁,嘿嘿 比如我们下载screen1.JPG中,突然掉线了,我们就可以这样开始续传 curl -c -O http://cgi2.tky.3wb.ne.jp/zzh/screen1.JPG 当然,你不要拿个flashget下载了一半的文件来糊弄我~~~~别的下载软件的半截文件可不一定能用哦~~~ 分块下载,我们使用这个option就可以了: -r 举例说明 比如我们有一个http://cgi2.tky.3web.ne.jp/~zzh/zhao1.mp3 要下载(赵老师的电话朗诵 :D ) 我们就可以用这样的命令: curl -r 0-10240 -o “zhao.part1” http:/cgi2.tky.3web.ne.jp/zzh/zhao1.mp3 & curl -r 10241-20480 -o “zhao.part1” http:/cgi2.tky.3web.ne.jp/zzh/zhao1.mp3 & curl -r 20481-40960 -o “zhao.part1” http:/cgi2.tky.3web.ne.jp/zzh/zhao1.mp3 & curl -r 40961- -o “zhao.part1” http:/cgi2.tky.3web.ne.jp/zzh/zhao1.mp3 这样就可以分块下载啦。 不过你需要自己把这些破碎的文件合并起来 如果你用UNIX或苹果,用 cat zhao.part* > zhao.mp3就可以 如果用的是Windows,用copy /b 来解决吧,呵呵 上面讲的都是http协议的下载,其实ftp也一样可以用。 用法嘛, curl -u name:passwd ftp://ip:port/path/file 或者大家熟悉的 curl ftp://name:passwd@ip:port/path/file 10)上传的option是 -T 比如我们向ftp传一个文件: curl -T localfile -u name:passwd ftp://upload\_site:port/path/ 当然,向http服务器上传文件也可以 比如 curl -T localfile http://cgi2.tky.3web.ne.jp/~zzh/abc.cgi 注意,这时候,使用的协议是HTTP的PUT method 刚才说到PUT,嘿嘿,自然让老服想起来了其他几种methos还没讲呢! GET和POST都不能忘哦。 http提交一个表单,比较常用的是POST模式和GET模式 GET模式什么option都不用,只需要把变量写在url里面就可以了 比如: curl http://www.yahoo.com/login.cgi?user=nickwolfe&password=12345 而POST模式的option则是 -d 比如,curl -d “user=nickwolfe&password=12345” http://www.yahoo.com/login.cgi 就相当于向这个站点发出一次登陆申请~~~~~ 到底该用GET模式还是POST模式,要看对面服务器的程序设定。 一点需要注意的是,POST模式下的文件上的文件上传,比如

这样一个HTTP表单,我们要用curl进行模拟,就该是这样的语法: curl -F upload=@localfile -F nick=go http://cgi2.tky.3web.ne.jp/~zzh/up\_file.cgi 罗罗嗦嗦讲了这么多,其实curl还有很多很多技巧和用法 比如 https的时候使用本地证书,就可以这样 curl -E localcert.pem https://remote\_server 再比如,你还可以用curl通过dict协议去查字典~~~~~ curl dict://dict.org/d:computer 今天为了检查所有刺猬主机上所有域名是否有备案.在使用wget不爽的情况下,找到了curl这个命令行流量器命令.发现其对post的调用还是蛮好的.特别有利于对提交信息及变 更参数进行较验.对于我想将几十万域名到miibeian.gov.cn进行验证是否有备案信息非常有用.发现这篇文章很不错,特为转贴. 我的目标: curl -d “cxfs=1&ym=xieyy.cn” http://www.miibeian.gov.cn/baxx\_cx\_servlet 在出来的信息中进行过滤,提取备案号信息,并设置一个标识位.将域名,备案号及标识位入库 用curl命令,post提交带空格的数据 今天偶然遇到一个情况,我想用curl登入一个网页,无意间发现要post的数据里带空格。比如用户名为”abcdef”,密码为”abc def”,其中有一个空格,按照我以前的方式提交: curl -D cookie -d “username=abcdef&password=abc def” http://login.xxx.com/提示登入失败。 于是查看curl手册man curl。找到: d/–data (HTTP) Sends the speci?ed data in a POST request to the HTTP server, in a way that can emulate as if a user has ?lled in a HTML form and pressed the submit button. Note that the data is sent exactly as speci?ed with no extra processing (with all newlines cut off). The data is expected to be “url-encoded”. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F/–form. If this option is used more than once on the same command line, the data pieces speci?ed will be merged together with a separating &-letter. Thus, using ’-d name=daniel -d skill=lousy’ would generate a post chunk that looks like ’name=daniel&skill=lousy’. 于是改用: curl -D cookie -d “username=abcdef” -d “password=abc efg” http://login.xxx.com/这样就能成功登入了。 (责任编辑:飘飞的夜) Curl是Linux下一个很强大的http命令行工具,其功能十分强大。 1) 二话不说,先从这里开始吧! $ curl http://www.linuxidc.com 回车之后,www.linuxidc.com 的html就稀里哗啦地显示在屏幕上了 ~ 2) 嗯,要想把读过来页面存下来,是不是要这样呢? $ curl http://www.linuxidc.com > page.html 当然可以,但不用这么麻烦的! 用curl的内置option就好,存下http的结果,用这个option: -o $ curl -o page.html http://www.linuxidc.com 这样,你就可以看到屏幕上出现一个下载页面进度指示。等进展到100%,自然就 OK咯 3) 什么什么?!访问不到?肯定是你的proxy没有设定了。 使用curl的时候,用这个option可以指定http访问所使用的proxy服务器及其端口: -x $ curl -x 123.45.67.89:1080 -o page.html http://www.linuxidc.com 4) 访问有些网站的时候比较讨厌,他使用cookie来记录session信息。 像IE/NN这样的浏览器,当然可以轻易处理cookie信息,但我们的curl呢?….. 我们来学习这个option: -D <— 这个是把http的response里面的cookie信息存到一个特别的文件中去 $ curl -x 123.45.67.89:1080 -o page.html -D cookie0001.txt http://www.linuxidc.com 这样,当页面被存到page.html的同时,cookie信息也被存到了cookie0001.txt里面了 5)那么,下一次访问的时候,如何继续使用上次留下的cookie信息呢?要知道,很多网站都是靠监视你的cookie信息,来判断你是不是不按规矩访问他们的网站的。 这次我们使用这个option来把上次的cookie信息追加到http request里面去: -b $ curl -x 123.45.67.89:1080 -o page1.html -D cookie0002.txt -b cookie0001.txt http://www.linuxidc.com 这样,我们就可以几乎模拟所有的IE操作,去访问网页了! 6)稍微等等 我好像忘记什么了 ~ 对了!是浏览器信息 有些讨厌的网站总要我们使用某些特定的浏览器去访问他们,有时候更过分的是,还要使用某些特定的版本 NND,哪里有时间为了它去找这些怪异的浏览器呢!? 好在curl给我们提供了一个有用的option,可以让我们随意指定自己这次访问所宣称的自己的浏览器信息: -A $ curl -A “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” -x 123.45.67.89:1080 -o page.html -D cookie0001.txt http://www.linuxidc.com 这样,服务器端接到访问的要求,会认为你是一个运行在Windows 2000上的 IE6.0,嘿嘿嘿,其实也许你用的是苹果机呢! 而”Mozilla/4.73 [en] (X11; U; Linux 2.2; 15 i686”则可以告诉对方你是一台 PC上跑着的Linux,用的是Netscape 4.73,呵呵呵 7)另外一个服务器端常用的限制方法,就是检查http访问的referer。比如你先访问首页,再访问里面所指定的下载页,这第二次访问的 referer地址就是第一次访问成功后的页面地址。这样,服务器端只要发现对下载页面某次访问的referer地址不是首页的地址,就可以断定那是个盗 连了 ~ 讨厌讨厌 ~我就是要盗连 ~!! 幸好curl给我们提供了设定referer的option: -e $ curl -A “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” -x 123.45.67.89:1080 -e “mail.linuxidc.com” -o page.html -D cookie0001.txt http://www.linuxidc.com 这样,就可以骗对方的服务器,你是从mail.linuxidc.com点击某个链接过来的了,呵呵呵 8)写着写着发现漏掉什么重要的东西了!——- 利用curl 下载文件 刚才讲过了,下载页面到一个文件里,可以使用 -o ,下载文件也是一样。比如, $ curl -o 1.jpg http://cgi2.tky.3web.ne.jp/zzh/screen1.JPG 这里教大家一个新的option: -O 大写的O,这么用: $ curl -O http://cgi2.tky.3web.ne.jp/~zzh/screen1.JPG 这样,就可以按照服务器上的文件名,自动存在本地了! 再来一个更好用的。 如果screen1.JPG以外还有screen2.JPG、screen3.JPG、….、screen10.JPG需要下载,难不成还要让我们写一个script来完成这些操作? 不干! 在curl里面,这么写就可以了: $ curl -O http://cgi2.tky.3web.ne.jp/~zzh/screen\[1-10\].JPG 呵呵呵,厉害吧?! ~ 9)再来,我们继续讲解下载! $ curl -O http://cgi2.tky.3web.ne.jp/~{zzh,nick}/\[001-201\].JPG 这样产生的下载,就是 zzh/001.JPG ~zzh/002.JPG … ~zzh/201.JPG ~nick/001.JPG ~nick/002.JPG … ~nick/201.JPG 够方便的了吧?哈哈哈 咦?高兴得太早了。 由于zzh/nick下的文件名都是001,002…,201,下载下来的文件重名,后面的把前面的文件都给覆盖掉了 ~ 没关系,我们还有更狠的! $ curl -o #2_#1.jpg http://cgi2.tky.3web.ne.jp/{zzh,nick}/[001-201].JPG —这是…..自定义文件名的下载? —对头,呵呵! 这样,自定义出来下载下来的文件名,就变成了这样:原来: ~zzh/001.JPG —-> 下载后: 001-zzh.JPG 原来: ~nick/001.JPG —-> 下载后: 001-nick.JPG 这样一来,就不怕文件重名啦,呵呵 ======================== function vpost($url, $data) { // 模拟提交数据函数 $curl = curl_init(); // 启动一个CURL会话 curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在 //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER[‘HTTP_USER_AGENT’]); // 模拟用户使用的浏览器 //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 //curl_setopt($curl, CURLOPT_COOKIEFILE, $GLOBALS[‘cookie_file’]); // 读取上面所储存的Cookie信息 //curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环 //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 //curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 $tmpInfo = curl_exec($curl); // 执行操作 if (curl_errno($curl)) { echo ‘Errno’ . curl_error($curl); } curl_close($curl); // 关键CURL会话 return $tmpInfo; // 返回数据 } //method=%E6%9F%A5%E8%AF%A2&jc=%E7%B2%A4&hphm=ahx843&hpzl=02&lxdh=8681&randcode2=9898 $url = “http://www@@@@@gdgajj@@@@@gov@@@@@cn/cx/wzss/wzss.do"; $fields_string = array ( “method” => “%E6%9F%A5%E8%AF%A2”, “jc” => “%E7%B2%A4”, “hphm” => “ahx843”, “hpzl”=>”02”, “lxdh”=>”8681”, “randcode2”=>”9898” );//应该改为”name=zhangsan&action=234234&age=20” echo $table = vpost($url, $fields_string);

当使用php5自带的file_get_contents方法来获取远程文件的时候,有时候会出现file_get_contents(): failed to open stream: HTTP request failed!这个警告信息。 google或者baidu一下,好多这样的问题,解决的方法都是修改php.ini,把allow_url_fopen给启用,改成 allow_url_fopen = On 这样做可以解决某些人的问题,有人说在php.ini中,有这样两个选项:allow_url_fopen =on(表示可以通过url打开远程文件),user_agent=”PHP”(表示通过哪种脚本访问网络,默认前面有个 “ ; “ 去掉即可。)重启服务器。 但是有些还是会有这个警告信息,想用完美的解决还差一步,还得设置php.ini里面的user_agent,php默认的user_agent是PHP,我们把它改成Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)来模拟浏览器就可以了 user_agent=”Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)” 在工作中遇到这个问题,后完美解决,故分享给大家。 我批量抓取chemblink的结构式发现循环后有部分图片无法显示,而远程文件是存在的。 抓取远程文件的时候出现类似Warning: readfile(http://www.php100.com/logo.gif) [function.readfile]: failed to open stream: HTTP request failed! 这样的警告信息,我使用的是 ob_start(); readfile(“http://www.php100.com/logo.gif"); $img = ob_get_contents(); ob_end_clean(); 这样在运行中会时不时的出现上述错误,我也换过file_get_contents等其他函数都没用用,在网上查阅后发现用CURL方法抓取不会出错 $url = “http://www.php100.com/logo.gif"; $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); $img = curl_exec($ch);

0%