PHP中 实现Get和POST请求

1、实现GET请求:获得网易的主页数据。

<?php
//本例的核心函数:fsockopen();

$url='www.163.com';//指定URL地址

$data = LinkURL($url);//调用LinkURL函数获得数据

print $data;//输出获得的数据


function LinkURL($url)
{
    //80是指端口,30是指超时时间
    $fp = @fsockopen($url, 80, $errno, $errstr, 30);
    if ($fp)
    {
        //我们必须得发送请求信息头,否则服务器不会返回数据。
        fputs($fp, "GET / HTTP/1.1\r\n");
        fputs($fp, "Host: $url\r\n");
        fputs($fp, "Accept: */*\r\n");
        fputs($fp, "Referer: http://$url/\r\n");
        fputs($fp, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)\r\n");
        fputs($fp, "Connection: Close\r\n\r\n");
    }
    while ($str = fread($fp, 4096))
    $data .= $str;
    fclose($fp);
    return $data;
}
?>

  2、实现POST请求,两种方式。

第一种方式:

<?php

$data=MovieSearch('I Love China');
print $data;

function MovieSearch($Text)
{
    $url='http://search1.china.com.cn/hlftiweb/searchcn.jsp';

    //POST数据
    $post_data['searchText'] = $Text;

    //解析URL地址
    $URL_Info=parse_url($url);
    foreach($post_data as $searchText=>$value)
        $values[]="$searchText=".urlencode($value);

    $data_string=implode("&",$values);
    //请求信息头
    $header.="Host: ".$URL_Info["host"]."\n";
    $header.="Referer: $url\n";
    $header.="User-Agent: Mozilla 4.0\r\n";
    $header.="Content-type: application/x-www-form-urlencoded\n";
    $header.="Content-length: ".strlen($data_string)."\n";
    $header.="Connection: close";

    //stream_context_create()提交请求信息。
    $opts['http']['method'] = 'POST';
    $opts['http']['header'] = $header;
    $opts['http']['content'] = $data_string;
    $context = stream_context_create($opts);
    $content = file($url, false, $context);
    $data = implode('', $content);
    return $data;
}

?>

第二种方式:

<?php
$data=MovieSearch('I Love China');
print $data;

function MovieSearch($Text)
{
    $url='http://search1.china.com.cn/hlftiweb/searchcn.jsp';

    $post_data['searchText'] = $Text;

    $URL_Info=parse_url($url);
       if(!isset($URL_Info["port"]))
        $URL_Info["port"]=80;
       foreach($post_data as $searchText=>$value)
        $values[]="$searchText=".urlencode($value);
    //POST数据
    $data_string=implode("&",$values);
    //请求信息头
    $header.="POST ".$URL_Info["path"]." HTTP/1.1\n";
    $header.="Host: ".$URL_Info["host"]."\n";
    $header.="Referer: $referrer\n";
    $header.="Content-type: application/x-www-form-urlencoded\n";
    $header.="Content-length: ".strlen($data_string)."\n";
    $header.="Connection: close\n";
    $header.="\n";
    $header.=$data_string."\n";
    //建立链接
    $fp = fsockopen($URL_Info["host"],$URL_Info["port"],$errorno,$errorstr,30);
    //发送请信息头
    fputs($fp, $header);
    //获得数据
    while ($str = @fread($fp, 4096))
        $data .= $str;
    fclose($fp);
    return $data;
}

最近在修改一个php的开源程序 需要学习一些php的东西。记录一下 

 

posted @ 2012-07-23 11:07  PandaIT  阅读(740)  评论(0编辑  收藏  举报