PHP Consuming RESTful APIs Fetching a URL with the POST Method and Form Data - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Consuming RESTful APIs Fetching a URL with the POST Method and Form Data - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, June 19, 2019

PHP Consuming RESTful APIs Fetching a URL with the POST Method and Form Data

PHP Consuming RESTful APIs




Fetching a URL with the POST Method and Form Data


Problem

You want to submit a document using the POST method, passing data formatted as an HTML form.

Solution

Set the method and content stream context options when using the http stream:

       $url = 'http://www.example.com/submit.php';
       // The submitted form data, encoded as query-string-style
       // name-value pairs
       $body = 'monkey=uncle&rhino=aunt';
       $options = array('method' => 'POST',
                                       'content' => $body,
                                       'header' => 'Content-type: application/x-www-form-urlencoded');
       // Create the stream context
       $context = stream_context_create(array('http' => $options));
       // Pass the context to file_get_contents()
       print file_get_contents($url, false, $context);

With cURL, set the CURLOPT_POST and CURLOPT_POSTFIELDS options:

       $url = 'http://www.example.com/submit.php';
       // The submitted form data, encoded as query-string-style
       // name-value pairs
       $body = 'monkey=uncle&rhino=aunt';
       $c = curl_init($url);
       curl_setopt($c, CURLOPT_POST, true);
       curl_setopt($c, CURLOPT_POSTFIELDS, $body);
       curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
       $page = curl_exec($c);
       curl_close($c);

Using HTTP_Request2, pass HTTP_Request2::METHOD_POST to setMethod() and chaincalls to addPostParameter() for each name/value pair in the data to submit:

       require 'HTTP/Request2.php';

       $url = 'http://www.example.com/submit.php';
       $r = new HTTP_Request2($url);

       $r->setMethod(HTTP_Request2::METHOD_POST)
               ->addPostParameter('monkey', 'uncle')
               ->addPostParameter('rhino','aunt');

       $page = $r->send()->getBody();

Discussion

Sending a POST method request requires different handling of any form arguments. In a GET request, these arguments are in the query string, but in a POST request, they go in the request body. Additionally, the request needs a Content-Length header that tells the server the size of the content to expect in the request body.

Although they each have different mechanisms by which you specify the request method and the body content, each of the examples in the Solution automatically add the proper Content-Length header for you.

If you use a stream context to send a POST request, make sure to set the method option to post. Case matters.


No comments:

Post a Comment

Post Top Ad