加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP模拟post提交的三种方法

发布时间:2020-12-13 05:17:55 所属栏目:PHP教程 来源:网络整理
导读:第一种方法:file_get_contents模拟post提交 代码如下: $data = array ('foo' => 'manongjc'); $data = http_build_query($data); $opts = array ( 'http' => array ( 'method' => 'POST', 'header'=> "Content-type: application/x-www-form-urlencodedrn"

第一种方法:file_get_contents模拟post提交

代码如下:

$data = array ('foo' => 'manongjc');

$data = http_build_query($data);

$opts = array (

'http' => array (

'method' => 'POST',

'header'=> "Content-type: application/x-www-form-urlencodedrn" .

"Content-Length: " . strlen($data) . "rn",

'content' => $data

)

);

$context = stream_context_create($opts);

$html = file_get_contents('http://xxx.com/post.php',false,$context);

echo $html;

?>

第二种方法:curl模拟post提交

代码如下:

$uri = "http://www.xxx.com/post.php";

// 参数数组

$data = array (

'name' => 'manongjc',

'password' => 'manongjc'

);

$ch = curl_init ();

curl_setopt ( $ch,CURLOPT_URL,$uri );

curl_setopt ( $ch,CURLOPT_POST,1 );

curl_setopt ( $ch,CURLOPT_HEADER,0 );

curl_setopt ( $ch,CURLOPT_RETURNTRANSFER,CURLOPT_POSTFIELDS,$data );

$return = curl_exec ( $ch );

curl_close ( $ch );

print_r($return);

第三种方法:socket模拟post提交

代码如下:

function socket_post($url,$post) {

$urls = parse_url($url);

if (!isset($urls['port'])) {

$urls['port'] = 80;

}

$fp = fsockopen($urls['host'],$urls['port'],$errno,$errstr);

if (!$fp) {

echo "$errno,$errstr";

exit();

}

$post = http_build_query($post);

$length = strlen($post);

$header = <<

POST {$urls['path']} HTTP/1.1

Host: {$urls['host']}

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

Content-Length: {$length}

Connection: close

{$post}

HEADER;

fwrite($fp,$header);

$result = '';

while (!feof($fp)) {

$result .= fread($fp,512);

}

$result = explode("rnrn",$result,2);

return $result[1];

}

$data = socket_post("http://www.xxx.com/post.php",array('name'=>'manongjc','email'=>'manongjc@gmail.com'));

var_dump($data);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读