php使用socket post数据到其它web服务器的方法
2015-06-02 10:29
811 查看
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']; }
希望本文所述对大家的php程序设计有所帮助。
您可能感兴趣的文章:
- php获取POST数据的三种方法实例详解
- PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)
- PHP利用超级全局变量$_POST来接收表单数据的实例
- PHP之将POST数据转化为字符串的实现代码
- PHP CURL post数据报错 failed creating formpost data
- php使用CURL模拟GET与POST向微信接口提交及获取数据的方法
- 功能强大的PHP POST提交数据类
- PHP模拟post提交数据方法汇总
- 利用PHP fsockopen 模拟POST/GET传送数据的方法
- php post大量数据时发现数据丢失问题解决方法
- 浅谈PHP接收POST数据方式
- PHP中使用socket方式GET、POST数据实例
- php程序内部post数据的方法
- PHP Post获取不到非表单数据的问题解决办法
相关文章推荐
- 一个关于if else容易迷惑的问题
- java-模拟tomcat服务器
- Linux socket 初步
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站
- PHP 5.3.0 安装分析心得
- apache 环境下 php 的配置注意事项
- 简单的Ruby中的Socket编程教程
- Socket不能选择本地IP连接问题如何解决