网上关于php bot程序的实例还是很少的,前段时间也是业务需求,开始接触此类程序,很有意思。所谓bot实际上是模拟get或post,去action一些程序,实现一些自动化处理,当然这个东西是双刃剑,可别使坏就好。
php实现bot有多种方式,个人比较喜欢httprequest,一来比较oo,而来编写简单方便。以下是class对应的function,还有一些examples。
function可以直接点击进入php官方的api,有意的朋友进去逛逛;方法名称很直观,不多解释。。
example #1 get example
代码
setoptions( array ( ' lastmodified ' => filemtime ( ' local.rss ' ))); $r -> addquerydata( array ( ' category ' => 3 )); try { $r -> send(); if ( $r -> getresponsecode() == 200 ) { file_put_contents ( ' local.rss ' , $r -> getresponsebody());}} catch (httpexception $ex ) { echo $ex ;} ?>
这个example模拟get去请求一个rss订阅器,还addquerydata这样的get查询参数,然后执行send,发送此get请求当getresponsecode是200时,也就是bot成功时,把get请求返回的response的html存入本地的文件中。
example #2 post example
代码 setoptions( array ( ' cookies ' => array ( ' lang ' => ' de ' ))); $r -> addpostfields( array ( ' user ' => ' mike ' , ' pass ' => ' s3c|r3t ' )); $r -> addpostfile( ' image ' , ' profile.jpg ' , ' image/jpeg ' ); try { echo $r -> send() -> getbody();} catch (httpexception $ex ) { echo $ex ;} ?>
这个example模拟post去请求一个php文件,post不是通过addquerydata这样的function,而是通过addpostfields来设置模拟的输入表单,然后执行send,把post请求返回的response的html echo到php当前页面中。