仅在php中使用http_build_query进行POST请求

时间:2013-07-24 06:40:42

标签: php post http-post

我需要使用 http_build_query 创建 POST 请求。以下是我的代码:

$uri_args = array (
  'name'         => 'Jack',
  'surname'      => 'Jackson',
  'username'     => 'jackson12',
  'email'        => 'Jack@mail.com',
);

$uri = http_build_query($uri_args);

header("Location: http://samplesite.com?$uri");

此刻它会生成像GET这样的请求,但我需要POST。 考虑到我不想使用curl,...只有 http_build_query

1 个答案:

答案 0 :(得分:4)

<?php

$data = array(
    'name' => 'Jack',
    'surname' => 'Jackson',
    'username' => 'jackson12',
    'email' => 'Jack@mail.com',
);

$query = http_build_query($data); 

// create context
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL,
        'content' => $query,
    ),
));

// send request and collect data    
$response = file_get_contents(
    $target = "http://example.com/target.php",
    $use_include_path = false,
    $context);

//some actions with $response
//...

// redirect
header("Location: http://samplesite.com");