首先我们来看一下file_get_contents函数原型
string file_get_contents ( string $filename [, bool $use_include_path [, resource $context [, int $offset [, int $maxlen ]]]] )
通过file_get_contents发送POST请求的重点就在$context参数上面,我们用stream_context_create()函数设置上下文。
stream_context_create()创建的上下文选项即可用于流(stream),也可用于文件系统(file system)。对于像 file_get_contents()、file_put_contents()、readfile()直接使用文件名操作而没有文件句柄的函数来说更有用。stream_context_create()增加header头只是一部份功能,还可以定义代理、超时等。
我们来看stream_context_create()函数的原型:
resource stream_context_create ([ array $options [, array $params ]] )
我们看到,通过传入设置数组用此函数来获取一个资源类型的上下文选项。
$postdata = http_build_query(
array(
\'var1\' => \'some content\',
\'var2\' => \'doh\'
)
);
/* http://www.manongjc.com/article/1426.html */
$opts = array(\'http\' =>
array(
\'method\' => \'POST\',
\'header\' => \'Content-type: application/x-www-form-urlencoded\',
\'content\' => $postdata
)
);
$context = stream_context_create($opts);
设置好上下文,我们通过file_get_contents()函数进行POST数据提交。
$result = file_get_contents(\'http://example.com/submit.php\', false, $context);
完整实例如下:
$postdata = http_build_query(
array(
\'var1\' => \'some content\',
\'var2\' => \'doh\'
)
);
$opts = array(\'http\' =>
array(
\'method\' => \'POST\',
\'header\' => \'Content-type: application/x-www-form-urlencoded\',
\'content\' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents(\'http://example.com/submit.php\', false, $context); 继续阅读与本文标签相同的文章
-
手机信号突然从“4G”变成“E”,是什么意思?客服给出答案
2026-05-14栏目: 教程
-
互联网架起“乌镇式生活”
2026-05-14栏目: 教程
-
微信才是内存“杀手”,别再乱清理,关闭这个功能,手机立马流畅
2026-05-14栏目: 教程
-
手机信号变成E是什么意思?看完专业人士给出的解释后,涨知识了
2026-05-14栏目: 教程
-
关于Word的四个隐藏办公小技巧,你可能一个也不知道,建议收藏!
2026-05-14栏目: 教程
