3

I need to create a POST request with http_build_query. Following are my codes:

$uri_args = array (
  'name'         => 'Jack',
  'surname'      => 'Jackson',
  'username'     => 'jackson12',
  'email'        => '[email protected]',
);

$uri = http_build_query($uri_args);

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

At the moment it generates a request like GET, but I need POST. Consider that I do not want to use curl, ... only http_build_query.

5

1 Answer 1

5
<?php

$data = array(
    'name' => 'Jack',
    'surname' => 'Jackson',
    'username' => 'jackson12',
    'email' => '[email protected]',
);

$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");
5
  • Thanks for your response, but where should I enter the uri (samplesite.com) I want it to be redirected to that address
    – user1847051
    Commented Jul 24, 2013 at 7:33
  • May you provide additional info? Do you want send request from other domain [ for example from (example.com/yourscript.php) to (samplesite.com) ] or do you want send request to script itself?
    – VenZell
    Commented Jul 24, 2013 at 7:43
  • I have updated my answer. I hope that I understand you correctly.
    – VenZell
    Commented Jul 24, 2013 at 8:07
  • look at this (header("Location: samplesite.com");) I want the (samplesite.com) address with generated post request like (samplesite.com?1239owlkjsdlasjdsa)
    – user1847051
    Commented Jul 24, 2013 at 8:18
  • 1
    As far as I know, in this situation, there's only one solution: you have to create a form as HTML - then use javascript to submit it. And you can't generate such string for a POST request...
    – VenZell
    Commented Jul 24, 2013 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.