php 中使用 file_get_contents 发送数据
其实我挺喜欢 file_get_contents
的,感觉很轻量,一般的 GET
或者 POST
都能胜任,自用的话,没必要动不动就拿出重量级的 CURL
,今天就简单写写在 php 中如何使用 file_get_contents
发送数据。
直接获取网页或文件内容
$url="https://notes.zeng.love";
$result=file_get_contents($url);
echo $result;
发送数据
$posturl="https://notes.zeng.love";
$post_data = array(
'key1' => 'value1',
'key2' => 'value2'
);
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',//发送方式,post或get
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($posturl, false, $context);
echo $result;
封装成函数
function send_data($url, $post_data) {
$postdata = http_build_query($post_data);//格式化数据
$options = array(
'http' => array(
'method' => 'POST',//发送方式,post或get
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
使用时调用
$posturl="https://notes.zeng.love";
$post_data = array(
'key1' => 'value1',
'key2' => 'value2'
);
$res=send_data($posturl, $post_data);
当然,不得不说,file_get_contents
在使用过程中,会出现一些始料未及的错误,功能也不够强大,为了使您的程序最大限度的兼容,还是推荐使用 curl
。
本文由[ Dazeng ]在[ 曾先生记事本 ]发布,转载请注明出处。