php 通过socket 发送数据到其它服务器的功能实例

模拟post数据到其它web server,php通过socket post数据到其它网页服务器,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

/**
 * 模拟post数据到其它服务器
 *
 * @param 
 * @arrange (编程之家) jb51.cc
 **/
function post_request($url,$data,$referer='') {
 
    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);
 
    // parse the given URL
    $url = parse_url($url);
 
    if ($url['scheme'] != 'http') { 
        die('Error: Only HTTP request are supported !');
    }
 
    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];
 
    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host,80,$errno,$errstr,30);
 
    if ($fp){
 
        // send the request headers:
        fputs($fp,POST $path HTTP/1.1\r\n);
        fputs($fp,Host: $host\r\n);
 
        if ($referer != '')
            fputs($fp,Referer: $referer\r\n);
 
        fputs($fp,Content-type: application/x-www-form-urlencoded\r\n);
        fputs($fp,Content-length: . strlen($data) .\r\n);
        fputs($fp,Connection: close\r\n\r\n);
        fputs($fp,$data);
 
        $result = ''; 
        while(!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp,128);
        }
    }
    else { 
        return array(
            'status' => 'err','error' => $errstr ($errno)
        );
    }
 
    // close the socket connection:
    fclose($fp);
 
    // split the result header from the content
    $result = explode(\r\n\r\n,$result,2);
 
    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';
 
    // return as structured array:
    return array(
        'status' => 'ok','header' => $header,'content' => $content
    );
}

//使用方法
// Submit those variables to the server
$post_data = array(
    'test' => 'foobar','okay' => 'yes','number' => 2
);
 
// Send a request to example.com 
$result = post_request('http://www.example.com/',$post_data);
 
if ($result['status'] == 'ok'){
 
    // Print headers 
    echo $result['header']; 
 
    echo '<hr />';
 
    // print the result of the whole request:
    echo $result['content'];
 
}
else {
    echo 'A error occured: ' . $result['error']; 
}


/***   来自编程之家 jb51.cc(jb51.cc)   ***/

相关文章

文章浏览阅读8.4k次,点赞8次,收藏7次。SourceCodester Onl...
文章浏览阅读3.4k次,点赞46次,收藏51次。本文为大家介绍在...
文章浏览阅读1.1k次。- php是最优秀, 最原生的模板语言, 替代...
文章浏览阅读1.1k次,点赞18次,收藏15次。整理K8s网络相关笔...
文章浏览阅读1.2k次,点赞22次,收藏19次。此网络模型提供了...
文章浏览阅读1.1k次,点赞14次,收藏19次。当我们谈论网络安...