php:用fsockopen伪装发送post语句并接受页面

fsockopen是socket API(原理和作用方法一直在学习中)的一种应用。

学习后台的时候,我们会用到小偷技术,来抓取一下页面。
一般情况下,fopen()函数就够用了,如抓取一个百度首页,或者抓取华东交通大学的课程表(用get方法提交的)。
但是form并不是只有get方法提交,还有一个不显示的post方法,这种页面的返回数据要抓取下来就不能用fopen函数了。

在网上查了很多资料,总结了一下内容,供大家分享。
post的本质就是发送给目的程序一个标志为post的协议串如下:

 
    POST /目的程序 HTTP/1.1

    Accept: */*

    Referer: http://www.phpiask.com

    Accept-Language: zh-cn,en-us;q=0.5

    Content-Type: application/x-www-form-urlencoded

    User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; .NET CLR 1.0.3705; .NET CLR 1.1.4322)

    Host: 要发送到的主机地址

    Content-Length: 发送数据的长度

    Pragma: no-cache

    Cache-Control: no-cache

    username=php&password=iask   //post发送的数据

 

首先我们用建立socket信道,在php中非常的简单
fsockopen(主机名称,端口号码,错误号的接受变量,错误提示的接受变量,超时时间)
然后可以利用fputs()函数提交post内容和fread()函数读取页面内容。
下面附上代码,自己研究吧。

    <?php

            $purl="http://xx网址:80/XXXXX/XXXXX.php?id=123&name=xiashuo";

            $info=parse_url($purl);

            print_r($info);

            $fp=fsockopen($info["host"],80,$errno,$errstr,30);

            if(!$fp){

                    echo "$errstr->$errno";

                    exit();

            }else {

                    $head="POST ".$info['path']."?".$info['query']." HTTP/1.0\r\n";

                    $head.="Host: ".$info['host']."\r\n";

                    $head.="Referer: http://localhost\r\n";

                    $head.="Content-type: application/x-www-form-urlencoded\r\n";

                    $head.="Content-Length: ".strlen(trim($info['query']))."\r\n";               

                    $head.="Connection: Close\r\n\r\n";

                    $head.=trim($info['query'])."\r\n";

                    fputs($fp, $head);

                    while (!feof($fp)){

                        $line = fread($fp,1024);

                        echo $line;

                }

            }

    ?>

 

不要再lamp环境中使用该方法,因为lamp环境中的80端口很多情况下不能使用。上面的代码,除网址有改动外,已经试验过能成功!
同作者:来自蓝盾社区www.ecjtu.org

你可能感兴趣的:(post)