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

Encrypting/decrypting without mcrypt

It is a little-known fact among members of the general PHP community that the mcrypt extension, the core of most PHP-based encryption considered secure, is anything but secure. One of the biggest issues, from a security perspective, is that the mcrypt extension requires advanced knowledge of cryptography to successfully operate, which few programmers have. This leads to gross misuse and ultimately problems such as a 1 in 256 chance of data corruption. Not good odds. Furthermore, developer support for libmcrypt, the core library upon which the mcrypt extension is based, was abandoned in 2007, which means the code base is out-of-date, bug-ridden, and has no mechanism to apply patches. Accordingly, it is extremely important to understand how to perform strong encryption/decryption without using mcrypt!

How to do it...

  1. The solution to the problem posed previously, in case you're wondering, is to use openssl. This extension is well maintained, and has modern and very strong encryption/decryption capabilities.

    Tip

    Important

    In order to use any openssl* functions, the openssl PHP extension must be compiled and enabled! In addition, you will need to install the latest OpenSSL package on your web server.

  2. First, you will need to determine which cipher methods are available on your installation. For this purpose, you can use the openssl_get_cipher_methods() command. Examples will include algorithms based on Advanced Encryption Standard (AES), BlowFish (BF), CAMELLIA, CAST5, Data Encryption Standard (DES), Rivest Cipher (RC) (also affectionately known as Ron's Code), and SEED. You will note that this method shows cipher methods duplicated in upper and lowercase.
  3. Next, you will need to figure out which method is most appropriate for your needs. Here is a table that gives a quick summary of the various methods:

    Method

    Published

    Key size (bits)

    Key block size (bytes)

    Notes

    camellia

    2000

    128, 192, 256

    16

    Developed by Mitsubishi and NTT

    aes

    1998

    128, 192, 256

    16

    Developed by Joan Daemen and Vincent Rijmen. Originally submitted as Rijndael

    seed

    1998

    128

    16

    Developed by the Korea Information Security Agency

    cast5

    1996

    40 to 128

    8

    Developed by Carlisle Adams and Stafford Tavares

    bf

    1993

    1 to 448

    8

    Designed by Bruce Schneier

    rc2

    1987

    8 to 1,024

    defaults to 64

    8

    Designed by Ron Rivest (one of the core founders of RSA)

    des

    1977

    56 (+8 parity bits)

    8

    Developed by IBM, based on work done by Horst Feistel

  4. Another consideration is what your preferred block cipher mode of operation is. Common choices are summarized in this table:

    Mode

    Stands For

    Notes

    ECB

    Electronic Code Book

    Does not require initialization vector (IV); supports parallelization for both encryption and decryption; simple and fast; does not hide data patterns; not recommended!!!

    CBC

    Cipher Block Chaining

    Requires IV; subsequent blocks, even if identical, are XOR'ed with previous block, resulting in better overall encryption; if the IVs are predictable, the first block can be decoded, leaving remaining message exposed; message must be padded to a multiple of the cipher block size; supports parallelization only for decryption

    CFB

    Cipher Feedback

    Close relative of CBC, except that encryption is performed in reverse

    OFB

    Output Feedback

    Very symmetrical: encrypt and decrypt are the same; does not supports parallelization at all

    CTR

    Counter

    Similar in operation to OFB; supports parallelization for both encryption and decryption

    CCM

    Counter with CBC-MAC

    Derivative of CTR; only designed for block length of 128 bits; provides authentication and confidentiality; CBC-MAC stands for Cipher Block Chaining - Message Authentication Code

    GCM

    Galois/Counter Mode

    Based on CTR mode; should use a different IV for each stream to be encrypted; exceptionally high throughput (compared to other modes); supports parallelization for both encryption and decryption

    XTS

    XEX-based Tweaked-codebook mode with ciphertext Stealing

    Relatively new (2010) and fast; uses two keys; increases the amount of data that can be securely encrypted as one block

  5. Before choosing a cipher method and mode, you will also need to determine whether the encrypted contents needs to be unencrypted outside of your PHP application. For example, if you are storing database credentials encrypted into a standalone text file, do you need to have the ability to decrypt from the command line? If so, make sure that the cipher method and operation mode you choose are supported by the target operating system.
  6. The number of bytes supplied for the IV varies according to the cipher method chosen. For best results, use random_bytes() (new in PHP 7), which returns a true CSPRNG sequence of bytes. The length of the IV varies considerably. Try a size of 16 to start with. If a warning is generated, the correct number of bytes to be supplied for that algorithm will be shown, so adjust the size accordingly:
    $iv  = random_bytes(16);
  7. To perform encryption, use openssl_encrypt(). Here are the parameters that should be passed:

    Parameter

    Notes

    Data

    Plain text you need to encrypt.

    Method

    One of the methods you identified using openssl_get_cipher_methods(). identified as follows:

    method - key_size - cipher_mode

    So, for example, if you want a method of AES, a key size of 256, and GCM mode, you would enter aes-256-gcm.

    Password

    Although documented as password, this parameter can be viewed as a key. Use random_bytes() to generate a key with a number of bytes to match the desired key size.

    Options

    Until you gain more experience with openssl encryption, it is recommended you stick with the default value of 0.

    IV

    Use random_bytes() to generate an IV with a number of bytes to match the cipher method.

  8. As an example, suppose you wanted to choose the AES cipher method, a key size of 256, and XTS mode. Here is the code used to encrypt:
    $plainText = 'Super Secret Credentials';
    $key = random_bytes(16);
    $method = 'aes-256-xts';
    $cipherText = openssl_encrypt($plainText, $method, $key, 0, $iv);
  9. To decrypt, use the same values for $key and $iv, along with the openssl_decrypt() function:
    $plainText = openssl_decrypt($cipherText, $method, $key, 0, $iv);

How it works...

In order to see which cipher methods are available, create a PHP script called chap_12_openssl_encryption.php and run this command:

<?php
echo implode(', ', openssl_get_cipher_methods());

The output should look something like this:

How it works...

Next, you can add values for the plain text to be encrypted, the method, key, and IV. As an example, try AES, with a key size of 256, using the XTS operating mode:

$plainText = 'Super Secret Credentials';
$method = 'aes-256-xts';
$key = random_bytes(16);
$iv  = random_bytes(16);

To encrypt, you can use openssl_encrypt(), specifying the parameters configured previously:

$cipherText = openssl_encrypt($plainText, $method, $key, 0, $iv);

You might also want to base 64-encode the result to make it more usable:

$cipherText = base64_encode($cipherText);

To decrypt, use the same $key and $iv values. Don't forget to un-encode the base 64 value first:

$plainText = openssl_decrypt(base64_decode($cipherText), 
$method, $key, 0, $iv);

Here is the output showing the base 64-encoded cipher text, followed by the decrypted plain text:

How it works...

If you supply an incorrect number of bytes for the IV, for the cipher method chosen, a warning message will be shown:

How it works...

There's more...

In PHP 7, there was a problem when using open_ssl_encrypt() and open_ssl_decrypt() and the Authenticated Encrypt with Associated Data (AEAD) modes supported: GCM and CCM. Accordingly, in PHP 7.1, three extra parameters have been added to these functions, as follows:

Parameter

Description

$tag

Authentication tag passed by reference; variable value remains the same if authentication fails

$aad

Additional authentication data

$tag_length

4 to 16 for GCM mode; no limits for CCM mode; only for open_ssl_encrypt()

For more information, you can refer to https://wiki.php.net/rfc/openssl_aead.

See also

For an excellent discussion on why the mcrypt extension is being deprecated in PHP 7.1, please refer to the article at https://wiki.php.net/rfc/mcrypt-viking-funeral. For a good description of block cipher, which forms the basis for the various cipher methods, refer to the article present at https://en.wikipedia.org/wiki/Block_cipher. For an excellent description of AES, refer to https://en.wikipedia.org/wiki/Advanced_Encryption_Standard. A good article that describes encryption operation modes can be seen at https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation.

Note

For some of the newer modes, if the data to be encrypted is less than the block size, openssl_decrypt() will return no value. If you pad the data to be at least the block size, the problem goes away. Most of the modes implement internal padding so this is not an issue. With some of the newer modes (that is, xts) you might see this problem. Be sure to conduct tests on short strings of data less than eight characters before putting your code into production.