编程语言
首页 > 编程语言> > POST请求仅在PHP中带有http_build_query

POST请求仅在PHP中带有http_build_query

作者:互联网

我需要使用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.

解决方法:

<?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");

标签:post,http-post,php
来源: https://codeday.me/bug/20191030/1969299.html