职业IT人-IT人生活圈

 找回密码
 成为会员
搜索
查看: 346|回复: 0

php中使用Curl、socket、file_get_contents三种方法POST提交数据``

[复制链接]
周周猪猪 发表于 2011-11-1 09:47 | 显示全部楼层 |阅读模式

<?php
/**
* Socket版本
* 使用方法:
* $post_string = "app=socket&version=beta";
* request_by_socket('jb51.net','/restServer.php',$post_string);
*/
function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){
$socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout);
if (!$socket) die("$errstr($errno)");
fwrite($socket,"POST $remote_path HTTP/1.0");
fwrite($socket,"User-Agent: Socket Example");
fwrite($socket,"HOST: $remote_server");
fwrite($socket,"Content-type: application/x-www-form-urlencoded");
fwrite($socket,"Content-length: ".strlen($post_string)+8."");
fwrite($socket,"Accept:*/*");
fwrite($socket,"");
fwrite($socket,"mypost=$post_string");
fwrite($socket,"");
$header = "";
while ($str = trim(fgets($socket,4096))) {
$header.=$str;
}
$data = "";
while (!feof($socket)) {
$data .= fgets($socket,4096);
}
return $data;
}
/**
* Curl版本
* 使用方法:
* $post_string = "app=request&version=beta";
* request_by_curl('http://jb51.net/restServer.php',$post_string);
*/
function request_by_curl($remote_server,$post_string){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$remote_server);
curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta");
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* 其它版本
* 使用方法:
* $post_string = "app=request&version=beta";
* request_by_other('http://jb51.net/restServer.php',$post_string);
*/
function request_by_other($remote_server,$post_string){
$context = array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type: application/x-www-form-urlencoded'."".
'User-Agent : Jimmy's POST Example beta'."".
'Content-length: '.strlen($post_string)+8,
'content'=>'mypost='.$post_string)
);
$stream_context = stream_context_create($context);
$data = file_get_contents($remote_server,FALSE,$stream_context);
return $data;
}
?>

该贴已经同步到 周周猪猪的微博
您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

QQ|手机版|小黑屋|网站帮助|职业IT人-IT人生活圈 ( 粤ICP备12053935号-1 )|网站地图
本站文章版权归原发布者及原出处所有。内容为作者个人观点,并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是信息平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽造成漏登,请及时联系我们,我们将根据著作权人的要求立即更正或者删除有关内容。

GMT+8, 2024-5-2 20:13 , Processed in 0.127979 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表