首先我们来看一下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);
收藏 打印