2

I have 2 files on a web server in the same directory: post.php and receive.php

The post.php file posts a username and password. The receive.php receives the username and password, and prints them out.

The receive.php file looks like this:

<?php
    $user=$_POST["user"];
    $password=$_POST["password"];
    echo("The Username is : ".$user."<br>");
    echo("The Password is : ".$password."<br>");
?>

I have this code for the post.php:

<?php
    $r = new HttpRequest('http://localhost/receive.php', HttpRequest::METH_POST);
    $r->addPostFields(array('user' => 'mike', 'password' => '1234'));
    try {
        echo $r->send()->getBody();
    } catch (HttpException $ex) {
        echo $ex;
    }
?>

I tried various different ways of coding the post.php file, but none of them worked. I also tried following some tutorials online, but that didn't work either. I'm a PHP noob, please help!!

Shivanshu Goyal
  • 1,374
  • 2
  • 16
  • 22

2 Answers2

4

The following code for post.php worked for me. I'm not 100% sure what it does, but it works.

<?php
$params = array ('user' => 'Mike', 'password' => '1234');

$query = http_build_query ($params);

// Create Http context details
$contextData = array ( 
            'method' => 'POST',
            'header' => "Connection: close\r\n".
                        "Content-Length: ".strlen($query)."\r\n",
            'content'=> $query );

// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));

// Read page rendered as result of your POST request
$result =  file_get_contents (
              'http://localhost/receive.php',  // page url
              false,
              $context);

// Server response is now stored in $result variable so you can process it
echo($result);
?>
Shivanshu Goyal
  • 1,374
  • 2
  • 16
  • 22
3

Sending HTTP request with PHP is possible but not trivial. Have a look at cURL, or better yet - a library like Artax.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308