php发送post请求方法大全附源码
日期:2020-05-14
来源:程序思维浏览:2472次
近期在做打印小票机的接口对接,要用post发送请求数据,现在教给大家如何用php发送post请求数据。
方法一:用stream_context_create和file_get_contents
<?php
/**
* 发送post请求
* @param string $url 请求地址
* @param array $post_data post键值对数据
* @return string
*/
function send_post($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
//测试
/*$post_data = array(
'username' => 'makalo',
'password' => 'makelochen'
);
echo send_post('http://localhost:8080/test.php', $post_data);*/
?>
方法二:使用curl
$data = array("admin"=>"pnzorcl");
$params=http_build_query($data);//转成admin=pnzorcl
$url = "http://localhost/29/submit.php?".$params;//请求的url地址
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
print_r($return);
源码下载链接:https://pan.baidu.com/s/1mb8DA48vY5aufk4jIjhwDw 密码:7w7m
方法一:用stream_context_create和file_get_contents
<?php
/**
* 发送post请求
* @param string $url 请求地址
* @param array $post_data post键值对数据
* @return string
*/
function send_post($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
//测试
/*$post_data = array(
'username' => 'makalo',
'password' => 'makelochen'
);
echo send_post('http://localhost:8080/test.php', $post_data);*/
?>
方法二:使用curl
$data = array("admin"=>"pnzorcl");
$params=http_build_query($data);//转成admin=pnzorcl
$url = "http://localhost/29/submit.php?".$params;//请求的url地址
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
$return = curl_exec ( $ch );
curl_close ( $ch );
print_r($return);
源码下载链接:https://pan.baidu.com/s/1mb8DA48vY5aufk4jIjhwDw 密码:7w7m
- 上一篇:js正则表达式知识大全
- 下一篇:前端面试必会DOM事件流、冒泡 、 捕获 、 委托
精品好课