Table of Contents for
PHP 7: Real World Application Development

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition PHP 7: Real World Application Development by Branko Ajzele Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. PHP 7: Real World Application Development
  4. PHP 7: Real World Application Development
  5. PHP 7: Real World Application Development
  6. Credits
  7. Preface
  8. What you need for this learning path
  9. Who this learning path is for
  10. Reader feedback
  11. Customer support
  12. 1. Module 1
  13. 1. Building a Foundation
  14. PHP 7 installation considerations
  15. Using the built-in PHP web server
  16. Defining a test MySQL database
  17. Installing PHPUnit
  18. Implementing class autoloading
  19. Hoovering a website
  20. Building a deep web scanner
  21. Creating a PHP 5 to PHP 7 code converter
  22. 2. Using PHP 7 High Performance Features
  23. Understanding the abstract syntax tree
  24. Understanding differences in parsing
  25. Understanding differences in foreach() handling
  26. Improving performance using PHP 7 enhancements
  27. Iterating through a massive file
  28. Uploading a spreadsheet into a database
  29. Recursive directory iterator
  30. 3. Working with PHP Functions
  31. Developing functions
  32. Hinting at data types
  33. Using return value data typing
  34. Using iterators
  35. Writing your own iterator using generators
  36. 4. Working with PHP Object-Oriented Programming
  37. Developing classes
  38. Extending classes
  39. Using static properties and methods
  40. Using namespaces
  41. Defining visibility
  42. Using interfaces
  43. Using traits
  44. Implementing anonymous classes
  45. 5. Interacting with a Database
  46. Using PDO to connect to a database
  47. Building an OOP SQL query builder
  48. Handling pagination
  49. Defining entities to match database tables
  50. Tying entity classes to RDBMS queries
  51. Embedding secondary lookups into query results
  52. Implementing jQuery DataTables PHP lookups
  53. 6. Building Scalable Websites
  54. Creating a generic form element generator
  55. Creating an HTML radio element generator
  56. Creating an HTML select element generator
  57. Implementing a form factory
  58. Chaining $_POST filters
  59. Chaining $_POST validators
  60. Tying validation to a form
  61. 7. Accessing Web Services
  62. Converting between PHP and XML
  63. Creating a simple REST client
  64. Creating a simple REST server
  65. Creating a simple SOAP client
  66. Creating a simple SOAP server
  67. 8. Working with Date/Time and International Aspects
  68. Using emoticons or emoji in a view script
  69. Converting complex characters
  70. Getting the locale from browser data
  71. Formatting numbers by locale
  72. Handling currency by locale
  73. Formatting date/time by locale
  74. Creating an HTML international calendar generator
  75. Building a recurring events generator
  76. Handling translation without gettext
  77. 9. Developing Middleware
  78. Authenticating with middleware
  79. Using middleware to implement access control
  80. Improving performance using the cache
  81. Implementing routing
  82. Making inter-framework system calls
  83. Using middleware to cross languages
  84. 10. Looking at Advanced Algorithms
  85. Using getters and setters
  86. Implementing a linked list
  87. Building a bubble sort
  88. Implementing a stack
  89. Building a binary search class
  90. Implementing a search engine
  91. Displaying a multi-dimensional array and accumulating totals
  92. 11. Implementing Software Design Patterns
  93. Creating an array to object hydrator
  94. Building an object to array hydrator
  95. Implementing a strategy pattern
  96. Defining a mapper
  97. Implementing object-relational mapping
  98. Implementing the Pub/Sub design pattern
  99. 12. Improving Web Security
  100. Filtering $_POST data
  101. Validating $_POST data
  102. Safeguarding the PHP session
  103. Securing forms with a token
  104. Building a secure password generator
  105. Safeguarding forms with a CAPTCHA
  106. Encrypting/decrypting without mcrypt
  107. 13. Best Practices, Testing, and Debugging
  108. Using Traits and Interfaces
  109. Universal exception handler
  110. Universal error handler
  111. Writing a simple test
  112. Writing a test suite
  113. Generating fake test data
  114. Customizing sessions using session_start parameters
  115. A. Defining PSR-7 Classes
  116. Implementing PSR-7 value object classes
  117. Developing a PSR-7 Request class
  118. Defining a PSR-7 Response class
  119. 2. Module 2
  120. 1. Setting Up the Environment
  121. Setting up Debian or Ubuntu
  122. Setting up CentOS
  123. Setting up Vagrant
  124. Summary
  125. 2. New Features in PHP 7
  126. New operators
  127. Uniform variable syntax
  128. Miscellaneous features and changes
  129. Summary
  130. 3. Improving PHP 7 Application Performance
  131. HTTP server optimization
  132. HTTP persistent connection
  133. Content Delivery Network (CDN)
  134. CSS and JavaScript optimization
  135. Full page caching
  136. Varnish
  137. The infrastructure
  138. Summary
  139. 4. Improving Database Performance
  140. Storage engines
  141. The Percona Server - a fork of MySQL
  142. MySQL performance monitoring tools
  143. Percona XtraDB Cluster (PXC)
  144. Redis – the key-value cache store
  145. Memcached key-value cache store
  146. Summary
  147. 5. Debugging and Profiling
  148. Profiling with Xdebug
  149. PHP DebugBar
  150. Summary
  151. 6. Stress/Load Testing PHP Applications
  152. ApacheBench (ab)
  153. Siege
  154. Load testing real-world applications
  155. Summary
  156. 7. Best Practices in PHP Programming
  157. Test-driven development (TDD)
  158. Design patterns
  159. Service-oriented architecture (SOA)
  160. Being object-oriented and reusable always
  161. PHP frameworks
  162. Version control system (VCS) and Git
  163. Deployment and Continuous Integration (CI)
  164. Summary
  165. A. Tools to Make Life Easy
  166. Git – A version control system
  167. Grunt watch
  168. Summary
  169. B. MVC and Frameworks
  170. Laravel
  171. Lumen
  172. Apigility
  173. Summary
  174. 3. Module 3
  175. 1. Ecosystem Overview
  176. Summary
  177. 2. GoF Design Patterns
  178. Structural patterns
  179. Behavioral patterns
  180. Summary
  181. 3. SOLID Design Principles
  182. Open/closed principle
  183. Liskov substitution principle
  184. Interface Segregation Principle
  185. Dependency inversion principle
  186. Summary
  187. 4. Requirement Specification for a Modular Web Shop App
  188. Wireframing
  189. Defining a technology stack
  190. Summary
  191. 5. Symfony at a Glance
  192. Creating a blank project
  193. Using Symfony console
  194. Controller
  195. Routing
  196. Templates
  197. Forms
  198. Configuring Symfony
  199. The bundle system
  200. Databases and Doctrine
  201. Testing
  202. Validation
  203. Summary
  204. 6. Building the Core Module
  205. Dependencies
  206. Implementation
  207. Unit testing
  208. Functional testing
  209. Summary
  210. 7. Building the Catalog Module
  211. Dependencies
  212. Implementation
  213. Unit testing
  214. Functional testing
  215. Summary
  216. 8. Building the Customer Module
  217. Dependencies
  218. Implementation
  219. Unit testing
  220. Functional testing
  221. Summary
  222. 9. Building the Payment Module
  223. Dependencies
  224. Implementation
  225. Unit testing
  226. Functional testing
  227. Summary
  228. 10. Building the Shipment Module
  229. Dependencies
  230. Implementation
  231. Unit testing
  232. Functional testing
  233. Summary
  234. 11. Building the Sales Module
  235. Dependencies
  236. Implementation
  237. Unit testing
  238. Functional testing
  239. Summary
  240. 12. Integrating and Distributing Modules
  241. Understanding GitHub
  242. Understanding Composer
  243. Understanding Packagist
  244. Summary
  245. Bibliography
  246. Index

Developing a PSR-7 Request class

One of the key characteristics of PSR-7 middleware is the use of Request and Response classes. When applied, this enables different blocks of software to perform together without sharing any specific knowledge between them. In this context, a request class should encompass all aspects of the original user request, including such items as browser settings, the original URL requested, parameters passed, and so forth.

How to do it...

  1. First, be sure to define classes to represent the Uri, Stream, and UploadedFile value objects, as described in the previous recipe.
  2. Now we are ready to define the core Application\MiddleWare\Message class. This class consumes Stream and Uri and implements Psr\Http\Message\MessageInterface. We first define properties for the key value objects, including those representing the message body (that is, a StreamInterface instance), version, and HTTP headers:
    namespace Application\MiddleWare;
    use Psr\Http\Message\ { 
      MessageInterface, 
      StreamInterface, 
      UriInterface 
    };
    class Message implements MessageInterface
    {
      protected $body;
      protected $version;
      protected $httpHeaders = array();
  3. Next, we have the getBody() method that represents a StreamInterface instance. A companion method, withBody(), returns the current Message instance and allows us to overwrite the current value of body:
    public function getBody()
    {
      if (!$this->body) {
          $this->body = new Stream(self::DEFAULT_BODY_STREAM);
      }
      return $this->body;
    }
    public function withBody(StreamInterface $body)
    {
      if (!$body->isReadable()) {
          throw new InvalidArgumentException(self::ERROR_BODY_UNREADABLE);
      }
      $this->body = $body;
      return $this;
    }
  4. PSR-7 recommends that headers should be viewed as case-insensitive. Accordingly, we define a findHeader() method (not directly defined by MessageInterface) that locates a header using stripos():
    protected function findHeader($name)
    {
      $found = FALSE;
      foreach (array_keys($this->getHeaders()) as $header) {
        if (stripos($header, $name) !== FALSE) {
            $found = $header;
            break;
        }
      }
      return $found;
    }
  5. The next method, not defined by PSR-7, is designed to populate the $httpHeaders property. This property is assumed to be an associative array where the key is the header, and the value is the string representing the header value. If there is more than one value, additional values separated by commas are appended to the string. There is an excellent apache_request_headers() PHP function from the Apache extension that produces headers if they are not already available in $httpHeaders:
    protected function getHttpHeaders()
    {
      if (!$this->httpHeaders) {
          if (function_exists('apache_request_headers')) {
              $this->httpHeaders = apache_request_headers();
          } else {
              $this->httpHeaders = $this->altApacheReqHeaders();
          }
      }
      return $this->httpHeaders;
    }
  6. If apache_request_headers() is not available (that is, the Apache extension is not enabled), we provide an alternative, altApacheReqHeaders():
    protected function altApacheReqHeaders()
    {
      $headers = array();
      foreach ($_SERVER as $key => $value) {
        if (stripos($key, 'HTTP_') !== FALSE) {
            $headerKey = str_ireplace('HTTP_', '', $key);
            $headers[$this->explodeHeader($headerKey)] = $value;
        } elseif (stripos($key, 'CONTENT_') !== FALSE) {
            $headers[$this->explodeHeader($key)] = $value;
        }
      }
      return $headers;
    }
    protected function explodeHeader($header)
    {
      $headerParts = explode('_', $header);
      $headerKey = ucwords(implode(' ', strtolower($headerParts)));
      return str_replace(' ', '-', $headerKey);
    }
  7. Implementing getHeaders() (required in PSR-7) is now a trivial loop through the $httpHeaders property produced by the getHttpHeaders() method discussed in step 4:
    public function getHeaders()
    {
      foreach ($this->getHttpHeaders() as $key => $value) {
        header($key . ': ' . $value);
      }
    }
  8. Again, we provide a series of with methods designed to overwrite or replace headers. Since there can be many headers, we also have a method that adds to the existing set of headers. The withoutHeader() method is used to remove a header instance. Notice the consistent use of findHeader(), mentioned in the previous step, to allow for case-insensitive handling of headers:
    public function withHeader($name, $value)
    {
      $found = $this->findHeader($name);
      if ($found) {
          $this->httpHeaders[$found] = $value;
      } else {
          $this->httpHeaders[$name] = $value;
      }
      return $this;
    }
    
    public function withAddedHeader($name, $value)
    {
      $found = $this->findHeader($name);
      if ($found) {
          $this->httpHeaders[$found] .= $value;
      } else {
          $this->httpHeaders[$name] = $value;
      }
      return $this;
    }
    
    public function withoutHeader($name)
    {
      $found = $this->findHeader($name);
      if ($found) {
          unset($this->httpHeaders[$found]);
      }
      return $this;
    }
  9. We then provide a series of useful header-related methods to confirm a header exists, retrieve a single header line, and retrieve a header in array form, as per PSR-7:
    public function hasHeader($name)
    {
      return boolval($this->findHeader($name));
    }
    
    public function getHeaderLine($name)
    {
      $found = $this->findHeader($name);
      if ($found) {
          return $this->httpHeaders[$found];
      } else {
          return '';
      }
    }
    
    public function getHeader($name)
    {
      $line = $this->getHeaderLine($name);
      if ($line) {
          return explode(',', $line);
      } else {
          return array();
      }
    }
  10. Finally, to round off header handling, we present getHeadersAsString that produces a single header string with the headers separated by \r\n for direct use with PHP stream contexts:
    public function getHeadersAsString()
    {
      $output = '';
      $headers = $this->getHeaders();
      if ($headers && is_array($headers)) {
          foreach ($headers as $key => $value) {
            if ($output) {
                $output .= "\r\n" . $key . ': ' . $value;
            } else {
                $output .= $key . ': ' . $value;
            }
          }
      }
      return $output;
    }
  11. Still within the Message class, we now turn our attention to version handling. According to PSR-7, the return value for the protocol version (that is, HTTP/1.1) should only be the numerical part. For this reason, we also provide onlyVersion() that strips off any non-digit character, allowing periods:
    public function getProtocolVersion()
    {
      if (!$this->version) {
          $this->version = $this->onlyVersion($_SERVER['SERVER_PROTOCOL']);
      }
      return $this->version;
    }
    
    public function withProtocolVersion($version)
    {
      $this->version = $this->onlyVersion($version);
      return $this;
    }
    
    protected function onlyVersion($version)
    {
      if (!empty($version)) {
          return preg_replace('/[^0-9\.]/', '', $version);
      } else {
          return NULL;
      }
    }
    
    }
  12. Finally, almost as an anticlimax, we are ready to define our Request class. It must be noted here, however, that we need to consider both out-bound as well as in-bound requests. That is to say, we need a class to represent an outgoing request a client will make to a server, as well as a request received from a client by a server. Accordingly, we provide Application\MiddleWare\Request (requests a client will make to a server), and Application\MiddleWare\ServerRequest (requests received from a client by a server). The good news is that most of our work has already been done: notice that our Request class extends Message. We also provide properties to represent the URI and HTTP method:
    namespace Application\MiddleWare;
    
    use InvalidArgumentException;
    use Psr\Http\Message\ { RequestInterface, StreamInterface, UriInterface };
    
    class Request extends Message implements RequestInterface
    {
      protected $uri;
      protected $method; // HTTP method
      protected $uriObj; // Psr\Http\Message\UriInterface instance
  13. All properties in the constructor default to NULL, but we leave open the possibility of defining the appropriate arguments right away. We use the inherited onlyVersion() method to sanitize the version. We also define checkMethod() to make sure any method supplied is on our list of supported HTTP methods, defined as a constant array in Constants:
    public function __construct($uri = NULL,
                                $method = NULL,
                                StreamInterface $body = NULL,
                                $headers = NULL,
                                $version = NULL)
    {
      $this->uri = $uri;
      $this->body = $body;
      $this->method = $this->checkMethod($method);
      $this->httpHeaders = $headers;
      $this->version = $this->onlyVersion($version);
    }
    protected function checkMethod($method)
    {
      if (!$method === NULL) {
          if (!in_array(strtolower($method), Constants::HTTP_METHODS)) {
              throw new InvalidArgumentException(Constants::ERROR_HTTP_METHOD);
          }
      }
      return $method;
    }
  14. We are going to interpret the request target as the originally requested URI in the form of a string. Bear in mind that our Uri class has methods that will parse this into its component parts, hence our provision of the $uriObj property. In the case of withRequestTarget(), notice that we run getUri() that performs the aforementioned parsing process:
    public function getRequestTarget()
    {
      return $this->uri ?? Constants::DEFAULT_REQUEST_TARGET;
    }
    
    public function withRequestTarget($requestTarget)
    {
      $this->uri = $requestTarget;
      $this->getUri();
      return $this;
    }
  15. Our get and with methods, which represent the HTTP method, reveal no surprises. We use checkMethod(), used in the constructor as well, to ensure the method matches those we plan to support:
    public function getMethod()
    {
      return $this->method;
    }
    
    public function withMethod($method)
    {
      $this->method = $this->checkMethod($method);
      return $this;
    }
  16. Finally, we have a get and with method for the URI. As mentioned in step 14, we retain the original request string in the $uri property and the newly parsed Uri instance in $uriObj. Note the extra flag to preserve any existing Host header:
    public function getUri()
    {
      if (!$this->uriObj) {
          $this->uriObj = new Uri($this->uri);
      }
      return $this->uriObj;
    }
    
    public function withUri(UriInterface $uri, $preserveHost = false)
    {
      if ($preserveHost) {
        $found = $this->findHeader(Constants::HEADER_HOST);
        if (!$found && $uri->getHost()) {
          $this->httpHeaders[Constants::HEADER_HOST] = $uri->getHost();
        }
      } elseif ($uri->getHost()) {
          $this->httpHeaders[Constants::HEADER_HOST] = $uri->getHost();
      }
      $this->uri = $uri->__toString();
      return $this;
      }
    }
  17. The ServerRequest class extends Request and provides additional functionality to retrieve information of interest to a server handling an incoming request. We start by defining properties that will represent incoming data read from the various PHP $_ super-globals (that is, $_SERVER, $_POST, and so on):
    namespace Application\MiddleWare;
    use Psr\Http\Message\ { ServerRequestInterface, UploadedFileInterface } ;
    
    class ServerRequest extends Request implements ServerRequestInterface
    {
    
      protected $serverParams;
      protected $cookies;
      protected $queryParams;
      protected $contentType;
      protected $parsedBody;
      protected $attributes;
      protected $method;
      protected $uploadedFileInfo;
      protected $uploadedFileObjs;
  18. We then define a series of getters to pull super-global information. We do not show everything, to conserve space:
    public function getServerParams()
    {
      if (!$this->serverParams) {
          $this->serverParams = $_SERVER;
      }
      return $this->serverParams;
    }
    // getCookieParams() reads $_COOKIE
    // getQueryParams() reads $_GET
    // getUploadedFileInfo() reads $_FILES
    
    public function getRequestMethod()
    {
      $method = $this->getServerParams()['REQUEST_METHOD'] ?? '';
      $this->method = strtolower($method);
      return $this->method;
    }
    
    public function getContentType()
    {
      if (!$this->contentType) {
          $this->contentType = $this->getServerParams()['CONTENT_TYPE'] ?? '';
          $this->contentType = strtolower($this->contentType);
      }
      return $this->contentType;
    }
  19. As uploaded files are supposed to be represented as independent UploadedFile objects (presented in the previous recipe), we also define a method that takes $uploadedFileInfo and creates UploadedFile objects:
    public function getUploadedFiles()
    {
      if (!$this->uploadedFileObjs) {
          foreach ($this->getUploadedFileInfo() as $field => $value) {
            $this->uploadedFileObjs[$field] = new UploadedFile($field, $value);
          }
      }
      return $this->uploadedFileObjs;
    }
  20. As with the other classes defined previously, we provide with methods that add or overwrite properties and return the new instance:
    public function withCookieParams(array $cookies)
    {
      array_merge($this->getCookieParams(), $cookies);
      return $this;
    }
    public function withQueryParams(array $query)
    {
      array_merge($this->getQueryParams(), $query);
      return $this;
    }
    public function withUploadedFiles(array $uploadedFiles)
    {
      if (!count($uploadedFiles)) {
          throw new InvalidArgumentException(Constant::ERROR_NO_UPLOADED_FILES);
      }
      foreach ($uploadedFiles as $fileObj) {
        if (!$fileObj instanceof UploadedFileInterface) {
            throw new InvalidArgumentException(Constant::ERROR_INVALID_UPLOADED);
        }
      }
      $this->uploadedFileObjs = $uploadedFiles;
    }
  21. One important aspect of PSR-7 messages is that the body should also be available in a parsed manner, that is to say, a sort of structured representation rather than just a raw stream. Accordingly, we define getParsedBody() and its accompanying with method. The PSR-7 recommendations are quite specific when it comes to form posting. Note the series of if statements that check the Content-Type header as well as the method:
    public function getParsedBody()
    {
      if (!$this->parsedBody) {
          if (($this->getContentType() == Constants::CONTENT_TYPE_FORM_ENCODED
               || $this->getContentType() == Constants::CONTENT_TYPE_MULTI_FORM)
               && $this->getRequestMethod() == Constants::METHOD_POST)
          {
              $this->parsedBody = $_POST;
          } elseif ($this->getContentType() == Constants::CONTENT_TYPE_JSON
                    || $this->getContentType() == Constants::CONTENT_TYPE_HAL_JSON)
          {
              ini_set("allow_url_fopen", true);
              $this->parsedBody = json_decode(file_get_contents('php://input'));
          } elseif (!empty($_REQUEST)) {
              $this->parsedBody = $_REQUEST;
          } else {
              ini_set("allow_url_fopen", true);
              $this->parsedBody = file_get_contents('php://input');
          }
      }
      return $this->parsedBody;
    }
    
    public function withParsedBody($data)
    {
      $this->parsedBody = $data;
      return $this;
    }
  22. We also allow for attributes that are not precisely defined in PSR-7. Rather, we leave this open so that the developer can provide whatever is appropriate for the application. Notice the use of withoutAttributes() that allows you to remove attributes at will:
    public function getAttributes()
    {
      return $this->attributes;
    }
    public function getAttribute($name, $default = NULL)
    {
      return $this->attributes[$name] ?? $default;
    }
    public function withAttribute($name, $value)
    {
      $this->attributes[$name] = $value;
      return $this;
    }
    public function withoutAttribute($name)
    {
      if (isset($this->attributes[$name])) {
          unset($this->attributes[$name]);
      }
      return $this;
    }
    
    }
  23. Finally, in order to load the different properties from an in-bound request, we define initialize(), which is not in PSR-7, but is extremely convenient:
    public function initialize()
    {
      $this->getServerParams();
      $this->getCookieParams();
      $this->getQueryParams();
      $this->getUploadedFiles;
      $this->getRequestMethod();
      $this->getContentType();
      $this->getParsedBody();
      return $this;
    }

How it works...

First, be sure to complete the preceding recipe, as the Message and Request classes consume Uri, Stream, and UploadedFile value objects. After that, go ahead and define the classes summarized in the following table:

Class

Steps they are discussed in

Application\MiddleWare\Message

2 to 9

Application\MiddleWare\Request

10 to 14

Application\MiddleWare\ServerRequest

15 to 20

After that, you can define a server program, chap_09_middleware_server.php, which sets up autoloading and uses the appropriate classes. This script will pull the incoming request into a ServerRequest instance, initialize it, and then use var_dump() to show what information was received:

<?php
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\MiddleWare\ServerRequest;

$request = new ServerRequest();
$request->initialize();
echo '<pre>', var_dump($request), '</pre>';

To run the server program, first change to the /path/to/source/for/this/chapter folder. You can then run the following command:

php -S localhost:8080 chap_09_middleware_server.php'

As for the client, first create a calling program, chap_09_middleware_request.php, that sets up autoloading, uses the appropriate classes, and defines the target server and a local text file:

<?php
define('READ_FILE', __DIR__ . '/gettysburg.txt');
define('TEST_SERVER', 'http://localhost:8080');
require __DIR__ . '/../Application/Autoload/Loader.php';
Application\Autoload\Loader::init(__DIR__ . '/..');
use Application\MiddleWare\ { Request, Stream, Constants };

Next, you can create a Stream instance using the text as a source. This will become the body of a new Request, which, in this case, mirrors what might be expected for a form posting:

$body = new Stream(READ_FILE);

You can then directly build a Request instance, supplying parameters as appropriate:

$request = new Request(
    TEST_SERVER,
    Constants::METHOD_POST,
    $body,
    [Constants::HEADER_CONTENT_TYPE => Constants::CONTENT_TYPE_FORM_ENCODED,Constants::HEADER_CONTENT_LENGTH => $body->getSize()]
);

Alternatively, you can use the fluent interface syntax to produce exactly the same results:

$uriObj = new Uri(TEST_SERVER);
$request = new Request();
$request->withRequestTarget(TEST_SERVER)
        ->withMethod(Constants::METHOD_POST)
        ->withBody($body)
        ->withHeader(Constants::HEADER_CONTENT_TYPE, Constants::CONTENT_TYPE_FORM_ENCODED)
        ->withAddedHeader(Constants::HEADER_CONTENT_LENGTH, $body->getSize());

You can then set up a cURL resource to simulate a form posting, where the data parameter is the contents of the text file. You can follow that with curl_init(), curl_exec(), and so on, echoing the results:

$data = http_build_query(['data' => $request->getBody()->getContents()]);
$defaults = array(
    CURLOPT_URL => $request->getUri()->getUriString(),
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data,
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
$response = curl_exec($ch);
curl_close($ch);

Here is how the direct output might appear:

How it works...

See also