通过curl发送和接收$ _POST

I am trying to write a simplified middle-tier that forwards $_POST received from front end and returns response received from the server side.

Following is my php for sending $_POST:

<?php
$username= 'testuser';
$password = '123' ;
$fields = array('username' => $username, 'password' => $password);
echo 'hello world' ; //checking
$url = 'url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

And this is the php file that receives the curl and just echoes back $_POST(for checking if it is received correctly).

<?php

if (isset($_POST["username"]) && !empty($_POST["username"])) {
    echo $_POST["username"];}

if (isset($_POST["password"]) && !empty($_POST["password"])) {
    echo $_POST["password"];}

?>

When i run this on my web server, I just get "Hello world" back. What do I need to change in order to get the response username/password back ?

It needs a query, not an array, like this:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

See: http://php.net/manual/en/function.http-build-query.php

I found this very useful tutorial to for sending standard $_POST requests and displaying their output: http://davidwalsh.name/curl-post

Here's my program that echoes the $_POST fields forwarded to a another php file, php program that sends:

<?php
//mid1.php
$username= 'testuser';
$password = '123' ;
$url = 'https://xxxx/mid2.php';
$fields = array('username' => urlencode($username),'password' => urlencode($password));
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
?>

Here is the php program that receives POST and just echoes back:

<?php
//mid2.php

if (isset($_POST["username"]) && !empty($_POST["username"])) {
    echo $_POST["username"];}

if (isset($_POST["password"]) && !empty($_POST["password"])) {
    echo $_POST["password"];}

?>