Full Code of codeguy/php-the-right-way for AI

gh-pages 20215da60bbd cached
120 files
411.9 KB
125.7k tokens
3 symbols
1 requests
Download .txt
Showing preview only (442K chars total). Download the full file or copy to clipboard to get everything.
Repository: codeguy/php-the-right-way
Branch: gh-pages
Commit: 20215da60bbd
Files: 120
Total size: 411.9 KB

Directory structure:
gitextract_5ktl7y4b/

├── .gitignore
├── .ruby-version
├── CNAME
├── CONTRIBUTING.md
├── Gemfile
├── Gruntfile.js
├── LICENSE
├── README.md
├── _config.yml
├── _includes/
│   └── welcome.md
├── _layouts/
│   ├── default.html
│   └── page.html
├── _posts/
│   ├── 01-01-01-Getting-Started.md
│   ├── 01-02-01-Use-the-Current-Stable-Version.md
│   ├── 01-03-01-Built-in-Web-Server.md
│   ├── 01-04-01-Mac-Setup.md
│   ├── 01-05-01-Windows-Setup.md
│   ├── 01-06-01-Linux-Setup.md
│   ├── 01-07-01-Common-Directory-Structure.md
│   ├── 02-01-01-Code-Style-Guide.md
│   ├── 03-01-01-Language-Highlights.md
│   ├── 03-02-01-Programming-Paradigms.md
│   ├── 03-03-01-Namespaces.md
│   ├── 03-04-01-Standard-PHP-Library.md
│   ├── 03-05-01-Command-Line-Interface.md
│   ├── 03-06-01-XDebug.md
│   ├── 04-01-01-Dependency-Management.md
│   ├── 04-02-01-Composer-and-Packagist.md
│   ├── 04-03-01-PEAR.md
│   ├── 05-01-01-Coding-Practices.md
│   ├── 05-02-01-The-Basics.md
│   ├── 05-03-01-Date-and-Time.md
│   ├── 05-04-01-Design-Patterns.md
│   ├── 05-05-01-PHP-and-UTF8.md
│   ├── 05-06-01-Internationalization-and-Localization.md
│   ├── 06-01-01-Dependency-Injection.md
│   ├── 06-02-01-Basic-Concept.md
│   ├── 06-03-01-Complex-Problem.md
│   ├── 06-04-01-Containers.md
│   ├── 06-05-01-Further-Reading.md
│   ├── 07-01-01-Databases.md
│   ├── 07-02-01-Databases_MySQL.md
│   ├── 07-03-01-Databases_PDO.md
│   ├── 07-04-01-Interacting-via-Code.md
│   ├── 07-05-01-Abstraction-Layers.md
│   ├── 08-01-01-Templating.md
│   ├── 08-02-01-Benefits.md
│   ├── 08-03-01-Plain-PHP-Templates.md
│   ├── 08-04-01-Compiled-Templates.md
│   ├── 08-05-01-Further-Reading.md
│   ├── 09-01-01-Errors-and-Exceptions.md
│   ├── 09-02-01-Errors.md
│   ├── 09-03-01-Exceptions.md
│   ├── 10-01-01-Security.md
│   ├── 10-02-01-Web-Application-Security.md
│   ├── 10-03-01-Password-Hashing.md
│   ├── 10-04-01-Data-Filtering.md
│   ├── 10-05-01-Configuration-Files.md
│   ├── 10-06-01-Register-Globals.md
│   ├── 10-07-01-Error-Reporting.md
│   ├── 11-01-01-Testing.md
│   ├── 11-02-01-Test-Driven-Development.md
│   ├── 11-03-01-Behavior-Driven-Development.md
│   ├── 11-04-01-Complementary-Testing-Tools.md
│   ├── 12-01-01-Servers-and-Deployment.md
│   ├── 12-02-01-Platform-as-a-Service.md
│   ├── 12-03-01-Virtual-or-Dedicated-Servers.md
│   ├── 12-04-01-Shared-Servers.md
│   ├── 12-05-01-Building-your-Application.md
│   ├── 13-01-01-Virtualization.md
│   ├── 13-02-01-Vagrant.md
│   ├── 13-03-01-Docker.md
│   ├── 14-01-01-Caching.md
│   ├── 14-02-01-Opcode-Cache.md
│   ├── 14-03-01-Object-Caching.md
│   ├── 15-01-01-Documenting.md
│   ├── 15-02-01-PHPDoc.md
│   ├── 16-01-01-Resources.md
│   ├── 16-02-01-From-the-Source.md
│   ├── 16-03-01-People-to-Follow.md
│   ├── 16-05-01-PHP-PaaS-Providers.md
│   ├── 16-06-01-Frameworks.md
│   ├── 16-07-01-Components.md
│   ├── 16-08-01-Sites.md
│   ├── 16-09-01-Videos.md
│   ├── 16-10-01-Books.md
│   ├── 17-01-01-Community.md
│   ├── 17-02-01-User-Groups.md
│   ├── 17-03-01-Conferences.md
│   └── 17-04-01-Elephpants.md
├── banners.md
├── css/
│   └── all.css
├── index.html
├── less/
│   └── all.less
├── package.json
├── pages/
│   ├── Design-Patterns.md
│   ├── Functional-Programming.md
│   ├── The-Basics.md
│   └── example.md
├── scripts/
│   ├── fastclick.js
│   └── setup.js
└── styles/
    ├── all.css
    ├── all.less
    ├── base/
    │   ├── all.less
    │   ├── bars-buttons.less
    │   ├── buttons.less
    │   ├── grid.less
    │   ├── idioms.less
    │   ├── prefixer.less
    │   ├── reset.less
    │   ├── spacing.less
    │   ├── typography.less
    │   └── variables.less
    ├── print.css
    ├── site/
    │   ├── site-content.less
    │   ├── site-footer.less
    │   ├── site-header.less
    │   ├── site-navigation.less
    │   └── variables.less
    └── syntax.css

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/_site/
*.DS_Store
node_modules
vendor
.bundle


================================================
FILE: .ruby-version
================================================
2.7.8


================================================
FILE: CNAME
================================================
phptherightway.com

================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to PHP The Right Way

Enjoy [PHP The Right Way](https://phptherightway.com) and want to get
involved? Great! There are plenty of ways you can help out.

Please take a moment to review this document in order to make the contribution
process easy and effective for everyone involved.

Following these guidelines helps to communicate that you respect the time of
the developers managing and developing this open source project. In return,
they should reciprocate that respect in addressing your issue or assessing
patches and features.


## Using the issue tracker

The [issue tracker](https://github.com/codeguy/php-the-right-way/issues) is
the preferred channel for changes: spelling mistakes, wording changes, new
content and generally [submitting pull requests](#pull-requests), but please
respect the following restrictions:

* Please **do not** use the issue tracker for personal support requests (use
  [Stack Overflow](https://stackoverflow.com/questions/tagged/php) or IRC).

* Please **do not** derail or troll issues. Keep the discussion on topic and
  respect the opinions of others.


<a name="pull-requests"></a>
## Pull Requests

Pull requests are a great way to add new content to PHP The Right Way, as well
as updating any browser issues or other style changes. Pretty much any sort of
change is accepted if seen as constructive.

Adhering to the following process is the best way to get your work
included in the project:

1. [Fork](https://docs.github.com/en/get-started/quickstart/fork-a-repo) the
   project, clone your fork, and configure the remotes:

   ```bash
   # Clone your fork of the repo into the current directory
   git clone https://github.com/<your-username>/php-the-right-way.git
   # Navigate to the newly cloned directory
   cd php-the-right-way
   # Assign the original repo to a remote called "upstream"
   git remote add upstream https://github.com/codeguy/php-the-right-way.git
   ```

2. If you cloned a while ago, get the latest changes from upstream:

   ```bash
   git checkout gh-pages
   git pull upstream gh-pages
   ```

3. Create a new topic branch (off the main project development branch) to
   contain your change or fix:

   ```bash
   git checkout -b <topic-branch-name>
   ```

4. Install the [Jekyll](https://github.com/jekyll/jekyll/) gem and dependencies to preview locally:

    ```bash
    # Install the needed gems through Bundler
    bundle install --path vendor/bundle
    # Run the local server
    bundle exec jekyll serve
    ```

5. Commit your changes in logical chunks. Please adhere to these [git commit
   message guidelines](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
   or your content is unlikely be merged into the main project. Use Git's
   [interactive rebase](https://docs.github.com/en/get-started/using-git/about-git-rebase)
   feature to tidy up your commits before making them public.

6. Locally merge (or rebase) the upstream development branch into your topic branch:

   ```bash
   git pull [--rebase] upstream gh-pages
   ```

7. Push your topic branch up to your fork:

   ```bash
   git push origin <topic-branch-name>
   ```

8. [Open a Pull Request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests)
    with a clear title and description.


## Contribution Agreement and Usage

By submitting a pull request to this repository, you agree to allow the project
owners to license your work under the the terms of the [Creative Commons Attribution-NonCommercial-ShareAlike
3.0 Unported License](https://creativecommons.org/licenses/by-nc-sa/3.0/).

The same content and license will be used for all PHP The Right Way publications,
including - but not limited to:

* [phptherightway.com](https://phptherightway.com)
* Translations of phptherightway.com
* [LeanPub: PHP The Right Way](https://leanpub.com/phptherightway/)
* Translations of "LeanPub: PHP The Right Way"

All content is completely free now, and always will be.

## Contributor Style Guide

1. Use American English spelling (*primary English repo only*)
2. Use four (4) spaces to indent text; do not use tabs
3. Wrap all text to 120 characters
4. Code samples should adhere to PSR-1 or higher
5. Use [GitHub Flavored Markdown](https://github.github.com/gfm/) for all content
6. Use language agnostic urls when referring to external websites such as the [php.net](https://www.php.net/urlhowto.php) manual


================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'
gem 'github-pages', group: :jekyll_plugins
gem 'rouge'


================================================
FILE: Gruntfile.js
================================================
module.exports = function(grunt) {
    // Project configuration
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        less: {
            dist: {
                options: {
                    cleancss: true,
                    compress: true,
                    ieCompat: true
                },
                files: {
                    "css/all.css": "less/all.less"
                }
            }
        },
        postcss: {
            options: {
                map: true,
                processors: [
                    require('autoprefixer')({
                        browsers: ['last 2 versions', 'ie 9']
                    })
                ]
            },
            dist: {
                src: 'css/all.css'
            }
        },
        watch: {
            less: {
                files: ['less/**/*.less'],
                tasks: ['less:dist', 'postcss:dist'],
                options: {
                    spawn: false
                }
            }
        }
    });

    // Load plugins
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-postcss');

    // Default task(s)
    grunt.registerTask('default', ['less', 'postcss:dist']);
};


================================================
FILE: LICENSE
================================================
Copyright (c) 2025 Josh Lockhart

https://creativecommons.org/licenses/by-nc-sa/3.0/


================================================
FILE: README.md
================================================
# PHP: The Right Way

## Overview

This is the GitHub Pages repository for the _PHP: The Right Way_ project.

* This website is a Jekyll project.
* Each section and sub-section are a Markdown file in `_posts/`.
* Sub-sections have `isChild: true` in their front matter.
* The navigation and page structure are automatically generated.

## Spread the Word!

_PHP: The Right Way_ has web banner images you can use on your website. Show your support, and let new PHP
developers know where to find good information!

[See Banner Images](https://www.phptherightway.com/banners.html)

## How to Contribute

You should read the `CONTRIBUTING.md` file for precise instructions and tips. But, if you prefer a TL;DR:

1. Fork and edit
2. Optionally install [Ruby](https://rvm.io/rvm/install/) with [Jekyll](https://github.com/mojombo/jekyll/) gem to preview locally
3. Submit pull request for consideration

### Contributor Style Guide

1. Use American English spelling (*primary English repo only*).
2. Use four (4) spaces to indent text; do not use tabs.
3. Wrap all text to 120 characters.
4. Code samples should adhere to PSR-1 or higher.

## Where

<https://www.phptherightway.com>

* [English](https://www.phptherightway.com)
* [Español](https://phpdevenezuela.github.io/php-the-right-way)
* [Français](https://eilgin.github.io/php-the-right-way/)
* [Indonesia](https://id.phptherightway.com)
* [Italiano](https://it.phptherightway.com)
* [Polski](https://pl.phptherightway.com)
* [Português do Brasil](https://br.phptherightway.com)
* [Română](https://bgui.github.io/php-the-right-way/)
* [Slovenščina](https://sl.phptherightway.com)
* [Srpski](https://phpsrbija.github.io/php-the-right-way/)
* [Türkçe](https://hkulekci.github.io/php-the-right-way/)
* [български](https://bg.phptherightway.com)
* [Русский язык](https://getjump.github.io/ru-php-the-right-way)
* [Українська](https://iflista.github.io/php-the-right-way/)
* [العربية](https://adaroobi.github.io/php-the-right-way/)
* [فارسى](https://novid.github.io/php-the-right-way/)
* [ภาษาไทย](https://apzentral.github.io/php-the-right-way/)
* [한국어판](https://modernpug.github.io/php-the-right-way)
* [日本語](https://ja.phptherightway.com)
* [简体中文](https://laravel-china.github.io/php-the-right-way/)
* [繁體中文](https://laravel-taiwan.github.io/php-the-right-way)

### Translations

If you are interested in translating _PHP: The Right Way_, fork this repo on GitHub and publish your localized fork to your own GitHub Pages account. We'll link to your translation from the primary document.

To avoid fragmentation and reader confusion, please choose one of these options:

1. We link to your GitHub Pages fork with `[username].github.io/php-the-right-way`
2. We link to your GitHub Pages fork with a subdomain (e.g. "ru.phptherightway.com")

If you use a subdomain, enter the subdomain into the `CNAME` file, and ask us to setup DNS for you. If you do not use a subdomain, remove the `CNAME` file entirely else your fork will not build when pushed.

Add information about your translation in the [wiki page](https://github.com/codeguy/php-the-right-way/wiki/Translations).

When your translation is ready, open an issue on the Issue Tracker to let us know.

## Why

There's been a lot of discussion lately about how the PHP community lacks sufficient, credible information for programmers new to PHP. This repository aims to solve this problem.

## Who

My name is [Josh Lockhart](https://x.com/codeguy). I'm the author of the [Slim Framework](https://www.slimframework.com/), and I work for [New Media Campaigns](https://www.newmediacampaigns.com/).

### Collaborators

* [Kris Jordan](https://krisjordan.com/)
* [Phil Sturgeon](https://phil.tech/)

## License

[Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License](https://creativecommons.org/licenses/by-nc-sa/3.0/)


================================================
FILE: _config.yml
================================================
baseurl: /
highlighter: rouge
markdown: kramdown
permalink: date
maruku:
    use_tex:    false
    use_divs:   false
    png_engine: blahtex
    png_dir:    images/latex
    png_url:    /images/latex

plugins:
    - jekyll-sitemap

defaults:
    -
      scope:
          path: ""
      values:
          sitemap: false
          image:
            path: /images/og-image.png
            width: 1024
            height: 640
            alt: "PHP: The Right Way"

# Excludes should be appended to the default
# https://github.com/jekyll/jekyll/blob/master/lib/site_template/_config.yml#L37-L55
exclude:
   - .sass-cache/
   - .jekyll-cache/
   - gemfiles/
   - Gemfile
   - Gemfile.lock
   - Gruntfile.js
   - node_modules/
   - package.json
   - vendor/bundle/
   - vendor/cache/
   - vendor/gems/
   - vendor/ruby/
   - CNAME
   - CONTRIBUTING.md
   - LICENSE
   - README.md
   - pages/example.md

future: true

title: "PHP: The Right Way"
tagline: Reference for PHP best practices
description: An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative PHP tutorials around the Web
logo: /images/og-image.png


================================================
FILE: _includes/welcome.md
================================================
# Welcome

There's a lot of outdated information on the Web that leads new PHP users astray,
propagating bad practices and insecure code. _PHP: The Right Way_ is an easy-to-read,
quick reference for PHP popular coding standards, links to authoritative tutorials
around the Web, and what the contributors consider to be best practices at present.

_There is no canonical way to use PHP_. This website aims to introduce new PHP
developers to some topics which they may not discover until it is too late, and aims
to give seasoned pros some fresh ideas on those topics they've been doing for years
without ever reconsidering. This website will also not tell you which tools to use, but
instead offer suggestions for multiple options, when possible explaining the differences
in approach and use-case.

This is a living document and will continue to be updated with more helpful information
and examples as they become available.

## Translations

_PHP: The Right Way_ is translated into many different languages:

* [English](https://www.phptherightway.com)
* [Español](https://phpdevenezuela.github.io/php-the-right-way)
* [Français](https://eilgin.github.io/php-the-right-way/)
* [Indonesia](https://id.phptherightway.com)
* [Italiano](https://it.phptherightway.com)
* [Polski](https://pl.phptherightway.com)
* [Português do Brasil](https://br.phptherightway.com)
* [Română](https://bgui.github.io/php-the-right-way/)
* [Slovenščina](https://sl.phptherightway.com)
* [Srpski](https://phpsrbija.github.io/php-the-right-way/)
* [Türkçe](https://hkulekci.github.io/php-the-right-way/)
* [български](https://bg.phptherightway.com)
* [Русский язык](https://getjump.github.io/ru-php-the-right-way)
* [Українська](https://iflista.github.io/php-the-right-way/)
* [العربية](https://adaroobi.github.io/php-the-right-way/)
* [فارسى](https://novid.github.io/php-the-right-way/)
* [ภาษาไทย](https://apzentral.github.io/php-the-right-way/)
* [한국어판](https://modernpug.github.io/php-the-right-way)
* [日本語](https://ja.phptherightway.com)
* [简体中文](https://laravel-china.github.io/php-the-right-way/)
* [繁體中文](https://laravel-taiwan.github.io/php-the-right-way)

## Book

The most recent version of _PHP: The Right Way_ is also available in PDF, EPUB and MOBI formats. [Go to Leanpub][1]

## How to Contribute

Help make this website the best resource for new PHP programmers! [Contribute on GitHub][2]

[1]: https://leanpub.com/phptherightway
[2]: https://github.com/codeguy/php-the-right-way/tree/gh-pages


================================================
FILE: _layouts/default.html
================================================
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>

        {% seo %}

        <meta name="robots" content="index,follow,archive"/>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <link rel="icon" href="{{ site.baseurl }}images/favicon.png" type="image/png"/>
        <link rel="stylesheet" href="{{ site.baseurl }}styles/syntax.css">
        <style>
        *{box-sizing:border-box}body{font-size:24px;line-height:32px;text-rendering:optimizeLegibility;word-wrap:break-word}h1,h2,h3,h4{font-family:georgia,serif}h1,.alpha{position:relative;font-size:48px;font-weight:normal;line-height:50px;text-align:center}h2,.beta{font-size:32px;font-weight:normal;line-height:36px}h3,.gamma{font-size:24px;font-weight:bold;line-height:30px}blockquote{border-left:3px solid #ccc;padding-left:20px;color:#777;font-style:italic;word-wrap:break-word}a{color:#4f5b93}a:hover{color:#8892bf}.back-to-top{text-align:center}.back-to-top a{background:#4f5b93;border-radius:3px;display:inline-block;height:40px;padding:0 20px;transition:all .1s ease;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-decoration:none;text-transform:uppercase}.back-to-top a:hover{background:#8892bf}img{max-width:100%}pre,code{color:#444;font-family:"Source Code Pro",Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:90%}a pre,a code{color:inherit}pre{background:#f7f7f7;border:1px solid #eee;border-radius:3px;display:block;overflow:auto;padding:20px;width:100%}@media (max-width:767px){body{font-size:18px;line-height:24px}h1,.alpha{font-size:36px;line-height:38px}h2,.beta{font-size:24px;line-height:28px}h3,.gamma{font-size:18px;line-height:23px}blockquote{margin-left:0}ul,ol{padding-left:1em}pre{padding:5px 10px}}@media (max-width:360px){body{font-size:16px;line-height:21px}h1,.alpha{font-size:28px;line-height:30px}h2,.beta{font-size:20px;line-height:23px}h3,.gamma{font-size:16px;line-height:20px}}.site-header{padding-top:40px;margin-bottom:40px;text-align:center}.site-header h1{margin:0;font-size:72px;line-height:60px}.site-header h1 em{display:block;font-size:34px;font-style:normal}.site-header h1 a{color:#333;text-decoration:none}.site-header h1 a:hover{color:#8892bf}.site-header .build-date{margin-bottom:10px;color:#999;font-family:verdana,sans-serif;font-size:11px;text-transform:uppercase}.site-header .btn-share{background:#8892bf;border-radius:3px;display:inline-block;height:30px;padding:0 20px;vertical-align:baseline;color:white;font-family:verdana,sans-serif;font-size:12px;line-height:30px;text-decoration:none;text-transform:uppercase}.site-header .fork-me{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAACVCAMAAABmfEh9AAAAMFBMVEXr6+wSFiH////U1NT09PSRk5hucHb5+flMT1f8/Py+v8EtMDpXWWE8P0hgY2rg4OD5mIG8AAAFoElEQVR4AbSb0W4sKQxEyxfMdAyG///b1bCt3MSZ1CKth4coj0fVVp0GevDnc318POqj9cvlv1efl9taC6j18fj4+JO7AlWtrY9LDtblboVg5VKh9XkdpTUIVjIVsJqcPUSSVi7VowJ4pjWOHuKViUWodljlcOR9XN1KCVhpVOERPrHGOBz5gJVJFcN6Yp2NfHiIiVQxrI0l1xFWXlqE6vMZltOCGCGtbKqIdVgQI6SVRMXS6m9teUJFsI6dGNLKpgpYMg5Hvoe0cqhCPzz4yGemRagSRj6klUsV0zp2Ykgrg+r/j7zPK6SVSxXTmr/Lp2miEwMVTYs5cQKa5URCFdPiI9+AAg0FEdJKpootP14l1cTQ8p0YqXhaEcpEuvbvqg5ppVPF2RrfoSoKNMeJnIr31vDvM9XE4Ektz6m4E/3zaTn2PE1pLdmJnIo78aa5FuryKJ8R08qm4k70hTaXSsSKs5VNxZ24a6GsN+x8OBV34jIRhYpHJ8aWT6WKacXXwFKGYokv28l9gYstn00V0/IvWL4A8/1XxKD8aCSTird8G3vk1bpVFeFOzKTiTtxQEpLaKzoxmYqPfMG8oXps+ejEZKqANfu4PhF8Q1UsLOdOTKfiThSDVW3TU5zIqc5bXh+q6In7RE5F0vIvI9+bmEUi7sQ8KpJWh95TluFETnXuxG5+14RmOJFTnRdEv6FQWsZpIKc6d+INpYYZsKITk6m4E0W8YEqrZZ6nlURFnNgXpvhaBRqxRkgrnYqcnbYmvjAES4Q7MZkqphWceD3jumrIijgxj4qcQTTsuLy3IdyJqVQxrYjl9wYDsAMnplLFtOLID0AHDvaJyVSk5duUAisN7acTQ1r5VMSJAu2G1eUFVkgrnYq8NK/SxebBDVk+FXHiRPGzG7J8KuLEoXc07YpYwYnZVAc3ZApUPbghS6EiTgxQNhR+cEOWTMVuyC5Yl4kmMcL4dppPRZzY6i76rhi85fOpyA1Zg46FpoBFKYaWz6cip4EK1KbV2kKPaY2QVjYVaXlvXauJtHodODGXijhRGqyLFHSJKzoxn4rtqkVkHyHF5cGJyVQxrXhd0A2fTa+DOzFSJaYVjkZ03VAGANq5EyNVXlrhq5F2Q6HoMH5DFqmS0/IfTrRqz5isMCfmU3EnNvyLMyd1Yj4Vc6Ksv5WlSpyYT8X2ibC//xbixHwq4kSpRaQXF3Fpkzoxn4o4cZkCTSZUuBPzqUjL68KGWq6m3In5VMSJNqVhecMWkDpxYjYV2fn4TkqswrooCndipMpMa351omN5N+hU0ScfcWI6FTmxmS62rXhDOXFiOhVp+WvZhsK+ZVn+qxPzqchm31FcFGvtAVv+uxPzqUha0/bj87UsjFb4aiSfijqx7Ygc4Ddk+VTciebPP4CJk31iPhV34iara+5p/7Xl86m4E3dSu7mM/LogUr3fid3Wbq4u+55T24u03kZFnOjSlu3jNxGF/fx1wduo+FcjBbK9+ITq8tOJ76LiX1Jabe2GelUQ76QiTuyGuqFg80VBvJeKONE21KsTm+G9vJWKOFE21OeJTTgaeTMVSasBl0jI6nYip8qfrW9O1AY0+bneTMW/GrEKqLxYPZ+KpBWPRmb7p307SEEoBoIoqBAlIOj9byt/9rUT3yaeoGhhGkmL/2VY9ZdOvBcqdGKtQifWKnRircILWa3CaiRX+cr3KndiqvIvn1TlJWWqcidaVV/5QIUl5baqTytXuROtKjqxVqETaxU6sVahE1uVNzaxCp0Yqny33jtVeUmZqnzlU5WvfKpyWqnKaaUqr0ZSlVcjqcqrkVqFTsxVeCFrVE7rM51oVZTWsLZVRVrjur5Eq4K0xnXtcaEKWbf1fEFVsca1HlBFrHEtvKWGrIFBlbHGheVA6ZoPVK2rV/18dX9UR3VUR3VUX8Uz94M6xyeLAAAAAElFTkSuQmCC);background-position:top right;background-repeat:no-repeat;background-size:contain;height:100px;width:100px;position:absolute;top:0;right:0;z-index:100;width:120px}.site-navigation,.site-content,.site-footer{margin:0 auto;max-width:840px;width:92%}.site-navigation{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:40px;-moz-column-gap:40px;column-gap:40px}.site-navigation input[type="checkbox"],.site-navigation label{display:none}.site-navigation ul{list-style:none;margin:0;padding:0}.site-navigation ul li{margin-bottom:20px;font-size:22px;line-height:23px}.site-navigation ul li a{display:block;color:#444;font-weight:700;text-decoration:none}.site-navigation ul li a:hover{color:#8892bf}.site-navigation ul li ul{padding-top:8px}.site-navigation ul li li{margin-bottom:6px;font-size:18px}.site-navigation ul li li a{border:none;color:#777;font-weight:normal}.site-navigation li{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}@media (max-width:820px){.site-navigation{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:560px){.site-navigation{-webkit-columns:1;-moz-columns:1;columns:1}}@media (max-width:375px){.site-navigation{background:rgba(255,255,255,0.95);-webkit-columns:1;-moz-columns:1;columns:1;max-height:100vh;position:fixed;bottom:0;left:0;z-index:100}.site-navigation label{background:#4f5b93;box-sizing:border-box;display:block;height:40px;padding:0 10px;width:100vh;position:absolute;bottom:0;left:0;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-transform:uppercase;z-index:2}.site-navigation>ul{background:rgba(255,255,255,0.96);border-top:3px solid #8892bf;box-shadow:rgba(0,0,0,0.25) 0 -5px 10px;box-sizing:border-box;padding:20px;overflow:auto;-webkit-overflow-scrolling:touch;position:absolute;left:0;bottom:40px;height:50vh;width:100vh;-webkit-transform:translate(0, 100vh);-ms-transform:translate(0, 100vh);transform:translate(0, 100vh);transition:all .2s ease;z-index:1}.site-navigation input[type="checkbox"]:checked~ul{-webkit-transform:translate(0, 0);-ms-transform:translate(0, 0);transform:translate(0, 0)}}.site-content h1{padding-top:40px;position:relative}.site-content h1:after{border:1px solid #ddd;border-bottom:none;content:"";display:block;height:8px;position:absolute;left:0;top:0;width:100%}.site-content.chapters{counter-reset:chapter}.site-content.chapters h1{counter-increment:chapter;padding-top:60px}.site-content.chapters h1:before{display:inline-block;content:"Chapter " counter(chapter) ".";position:absolute;top:30px;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);color:#999;font-size:12px;letter-spacing:1px;line-height:20px;text-transform:uppercase;text-align:center}.site-content #welcome ul{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:30px;-moz-column-gap:30px;column-gap:30px;list-style-position:inside}.site-content .back-to-top{margin-bottom:60px}@media (max-width:870px){.site-content #welcome ul{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:600px){.site-content #welcome ul{-webkit-columns:1;-moz-columns:1;columns:1}}.site-footer{border-top:1px solid #ccc;margin:60px auto 0 auto;padding:40px 20px;font-family:verdana,sans-serif;font-size:16px;text-align:center}.site-footer .cc-badge{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFgAAAAfCAMAAABUFvrSAAAAw1BMVEX///8AAAAAAACrsar///8oKSjR1NAODg4jHyDLz8pAPz/f399wcHBQUFBgYGDJzcjEyMN5fHkwMDC9wry4vbeAgIDw8PDBxcDO0c3M0MyUmJPGysW6v7q/v7+fn5/T1tKvtK61urSxt7C/w76zuLKhpKDk5OSRk5F2c3RQUVAbGxuts6yEhoR9fnxDREMgICDW1dXJyMirq6qvr68wLS3Pz8+Rj4+Pj4+LioqEgYJaV1i6ubmbl5meoJ1dXl06NjcZGRmWw6QEAAAAAnRSTlMMANomgjQAAAMCSURBVHjatZYJc6JAEIWznWFmOAQDguAdjUqMd0yi5vz/v2q7GTmkNusWW3kxNfJkPts3TMPVFfyIfiH3ttHwRs1623F0PYp03XHa9ebI6zRu74aDwcPDdQUBXCG3440Qq4ec91GchzqhM/J1FSEYuVguYudLASixnBM6JVPJNxqgtJts2mWHwMh1Ij6dQabZlEeKfDccDlo4xbAsA6e11KzLDoG9EXHvqVbb73Z9m+q+r4dEppLHAmomQ5k1EMmsi44CY74JV/gBU+ohWqtjzSMMY6iBjR4AfQAaTVLO87HkTDabiXIUuNnWieuaLFPgYs1cb1PJC6itUzCrwQ2mCe4bcr9EPEkdOmcsUa+Jo8B1J5wiF8s9J0/DpGQNCt9ogkbladKwwZ/DNnNMtpGfdizlMzkKjAXPQDyxMwUCZqpkMOjYBrBpNADnGDESZDxZ5w4L3uQec5A7chTYCecAPiupBzDHkr0OWHQIKBotwqCzidGI17kTSKlhzFJOyFFgvgSBQXRrhuGr4QUnCFhyzOIbMDLinZTH18y523UTsJmBdS7ARiCQjEcg2fTjBdfrzc6foqCsemwtUUbqvI43jG2lxHMyMACW6MLK7K56Lrjm46qXZNGnkE+LB5AvHjlHudtBvF3MUqcn5eGgybd88aI+AP4KlbMaSF0ERwj2ocZKlxs5k8OXeA6KzkGirICcfwI3ChvEKm6Q/bHkbLbbtXLKUQRPKx+joCGPorGttKXzxTutWrZ41mnxGrdjDcC1LTdvOZcddbndg2DZ5fZoJANbqcuNGtygWttMdvTLtxsE+1uFXp9vafO7LV0ZTE3o/S9NqBqXwLDQ+QeSC23IVG1zDtVFYLD0s0Yf+ALgk0cL+F8wLCL+Ubo18agFqdT+oDeZo/7RL53EzsGUxnvpZtoqzDm9WO6o49JXKaMIpjRCPk1v/1Me6sUc0rZZcE5/BaXtpAQGd4Bozul5BbEDAwoqB6GcrOLcLFesZOw99Yjl7Ql7oeIUXjynBP4h/djT5m+nuF33PcPucwAAAABJRU5ErkJggg==);background-position:top left;background-repeat:no-repeat;background-size:contain;display:inline-block;height:31px;width:88px}.site-footer h2{font-size:24px;font-weight:bold;line-height:30px;margin-bottom:10px}.site-footer ul{list-style:none;margin:0 0 20px 0;padding:0}.site-footer .license{color:#777;font-size:13px}
        </style>
    </head>
    <body>
        <header class="site-header">
            <h1><a href="/">PHP <em>The Right Way</em></a></h1>
            <div class="build-date">Last Updated: {{ site.time }}</div>
            <div class="share">
                <a class="btn-share" href="https://x.com/intent/tweet?text=PHP+The+Right+Way&amp;url=https%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on X</a>
            </div>
            <a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a>
        </header>

        <nav class="site-navigation">
            <input type="checkbox" id="toggle"/>
            <label for="toggle">Table of Contents</label>
            <ul>
                <li><a href="/#welcome">Welcome</a>
                    <ul>
                        <li><a href="/#translations">Translations</a></li>
                        <li><a href="/#how-to-contribute">How to Contribute</a></li>
                    </ul>
                </li>
                {% assign lastIsChild = false %}
                {% for post in site.posts reversed %}
                    {% if post.isChild != true %}
                        {% if insideSection %}
                            </ul>
                            </li>
                            {% assign insideSection = false %}
                        {% endif %}
                    {% endif %}
                    <li><a href="/#{{ post.anchor }}">{{ post.title }}</a>
                    {% if post.isChild %}
                        </li>
                    {% else %}
                        <ul>
                        {% assign insideSection = true %}
                    {% endif %}
                    {% assign lastIsChild = post.isChild %}
                {% endfor %}
                    </ul>
                </li>
                <li><a href="/#credits">Credits</a></li>
            </ul>
        </nav>

        <div class="site-content chapters">
            {{ content }}
        </div>

        <footer class="site-footer" id="credits">
            <h2>Created and maintained by</h2>
            <ul>
                <li><a href="https://joshlockhart.com" target="_blank">Josh Lockhart</a></li>
                <li><a href="https://philsturgeon.uk/" target="_blank">Phil Sturgeon</a></li>
                <li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li>
            </ul>
            <div class="license">
                <a class="cc-badge" rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/"></a>
                <br />
                <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a>
                <br/>
                is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>.
            </div>
        </footer>
    </body>
</html>


================================================
FILE: _layouts/page.html
================================================
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>

        {% seo %}

        <meta name="robots" content="index,follow,archive"/>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
        <link rel="icon" href="{{ site.baseurl }}images/favicon.png" type="image/png"/>
        <link rel="stylesheet" href="{{ site.baseurl }}styles/syntax.css">
        <style>
        *{box-sizing:border-box}body{font-size:24px;line-height:32px;text-rendering:optimizeLegibility;word-wrap:break-word}h1,h2,h3,h4{font-family:georgia,serif}h1,.alpha{position:relative;font-size:48px;font-weight:normal;line-height:50px;text-align:center}h2,.beta{font-size:32px;font-weight:normal;line-height:36px}h3,.gamma{font-size:24px;font-weight:bold;line-height:30px}blockquote{border-left:3px solid #ccc;padding-left:20px;color:#777;font-style:italic;word-wrap:break-word}a{color:#4f5b93}a:hover{color:#8892bf}.back-to-top{text-align:center}.back-to-top a{background:#4f5b93;border-radius:3px;display:inline-block;height:40px;padding:0 20px;transition:all .1s ease;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-decoration:none;text-transform:uppercase}.back-to-top a:hover{background:#8892bf}img{max-width:100%}pre,code{color:#444;font-family:"Source Code Pro",Consolas,"Andale Mono WT","Andale Mono","Lucida Console","Lucida Sans Typewriter","DejaVu Sans Mono","Bitstream Vera Sans Mono","Liberation Mono","Nimbus Mono L",Monaco,"Courier New",Courier,monospace;font-size:90%}a pre,a code{color:inherit}pre{background:#f7f7f7;border:1px solid #eee;border-radius:3px;display:block;overflow:auto;padding:20px;width:100%}@media (max-width:767px){body{font-size:18px;line-height:24px}h1,.alpha{font-size:36px;line-height:38px}h2,.beta{font-size:24px;line-height:28px}h3,.gamma{font-size:18px;line-height:23px}blockquote{margin-left:0}ul,ol{padding-left:1em}pre{padding:5px 10px}}@media (max-width:360px){body{font-size:16px;line-height:21px}h1,.alpha{font-size:28px;line-height:30px}h2,.beta{font-size:20px;line-height:23px}h3,.gamma{font-size:16px;line-height:20px}}.site-header{padding-top:40px;margin-bottom:40px;text-align:center}.site-header h1{margin:0;font-size:72px;line-height:60px}.site-header h1 em{display:block;font-size:34px;font-style:normal}.site-header h1 a{color:#333;text-decoration:none}.site-header h1 a:hover{color:#8892bf}.site-header .build-date{margin-bottom:10px;color:#999;font-family:verdana,sans-serif;font-size:11px;text-transform:uppercase}.site-header .btn-share{background:#8892bf;border-radius:3px;display:inline-block;height:30px;padding:0 20px;vertical-align:baseline;color:white;font-family:verdana,sans-serif;font-size:12px;line-height:30px;text-decoration:none;text-transform:uppercase}.site-header .fork-me{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAACVCAMAAABmfEh9AAAAMFBMVEXr6+wSFiH////U1NT09PSRk5hucHb5+flMT1f8/Py+v8EtMDpXWWE8P0hgY2rg4OD5mIG8AAAFoElEQVR4AbSb0W4sKQxEyxfMdAyG///b1bCt3MSZ1CKth4coj0fVVp0GevDnc318POqj9cvlv1efl9taC6j18fj4+JO7AlWtrY9LDtblboVg5VKh9XkdpTUIVjIVsJqcPUSSVi7VowJ4pjWOHuKViUWodljlcOR9XN1KCVhpVOERPrHGOBz5gJVJFcN6Yp2NfHiIiVQxrI0l1xFWXlqE6vMZltOCGCGtbKqIdVgQI6SVRMXS6m9teUJFsI6dGNLKpgpYMg5Hvoe0cqhCPzz4yGemRagSRj6klUsV0zp2Ykgrg+r/j7zPK6SVSxXTmr/Lp2miEwMVTYs5cQKa5URCFdPiI9+AAg0FEdJKpootP14l1cTQ8p0YqXhaEcpEuvbvqg5ppVPF2RrfoSoKNMeJnIr31vDvM9XE4Ektz6m4E/3zaTn2PE1pLdmJnIo78aa5FuryKJ8R08qm4k70hTaXSsSKs5VNxZ24a6GsN+x8OBV34jIRhYpHJ8aWT6WKacXXwFKGYokv28l9gYstn00V0/IvWL4A8/1XxKD8aCSTird8G3vk1bpVFeFOzKTiTtxQEpLaKzoxmYqPfMG8oXps+ejEZKqANfu4PhF8Q1UsLOdOTKfiThSDVW3TU5zIqc5bXh+q6In7RE5F0vIvI9+bmEUi7sQ8KpJWh95TluFETnXuxG5+14RmOJFTnRdEv6FQWsZpIKc6d+INpYYZsKITk6m4E0W8YEqrZZ6nlURFnNgXpvhaBRqxRkgrnYqcnbYmvjAES4Q7MZkqphWceD3jumrIijgxj4qcQTTsuLy3IdyJqVQxrYjl9wYDsAMnplLFtOLID0AHDvaJyVSk5duUAisN7acTQ1r5VMSJAu2G1eUFVkgrnYq8NK/SxebBDVk+FXHiRPGzG7J8KuLEoXc07YpYwYnZVAc3ZApUPbghS6EiTgxQNhR+cEOWTMVuyC5Yl4kmMcL4dppPRZzY6i76rhi85fOpyA1Zg46FpoBFKYaWz6cip4EK1KbV2kKPaY2QVjYVaXlvXauJtHodODGXijhRGqyLFHSJKzoxn4rtqkVkHyHF5cGJyVQxrXhd0A2fTa+DOzFSJaYVjkZ03VAGANq5EyNVXlrhq5F2Q6HoMH5DFqmS0/IfTrRqz5isMCfmU3EnNvyLMyd1Yj4Vc6Ksv5WlSpyYT8X2ibC//xbixHwq4kSpRaQXF3Fpkzoxn4o4cZkCTSZUuBPzqUjL68KGWq6m3In5VMSJNqVhecMWkDpxYjYV2fn4TkqswrooCndipMpMa351omN5N+hU0ScfcWI6FTmxmS62rXhDOXFiOhVp+WvZhsK+ZVn+qxPzqchm31FcFGvtAVv+uxPzqUha0/bj87UsjFb4aiSfijqx7Ygc4Ddk+VTciebPP4CJk31iPhV34iara+5p/7Xl86m4E3dSu7mM/LogUr3fid3Wbq4u+55T24u03kZFnOjSlu3jNxGF/fx1wduo+FcjBbK9+ITq8tOJ76LiX1Jabe2GelUQ76QiTuyGuqFg80VBvJeKONE21KsTm+G9vJWKOFE21OeJTTgaeTMVSasBl0jI6nYip8qfrW9O1AY0+bneTMW/GrEKqLxYPZ+KpBWPRmb7p307SEEoBoIoqBAlIOj9byt/9rUT3yaeoGhhGkmL/2VY9ZdOvBcqdGKtQifWKnRircILWa3CaiRX+cr3KndiqvIvn1TlJWWqcidaVV/5QIUl5baqTytXuROtKjqxVqETaxU6sVahE1uVNzaxCp0Yqny33jtVeUmZqnzlU5WvfKpyWqnKaaUqr0ZSlVcjqcqrkVqFTsxVeCFrVE7rM51oVZTWsLZVRVrjur5Eq4K0xnXtcaEKWbf1fEFVsca1HlBFrHEtvKWGrIFBlbHGheVA6ZoPVK2rV/18dX9UR3VUR3VUX8Uz94M6xyeLAAAAAElFTkSuQmCC);background-position:top right;background-repeat:no-repeat;background-size:contain;height:100px;width:100px;position:absolute;top:0;right:0;z-index:100;width:120px}.site-navigation,.site-content,.site-footer{margin:0 auto;max-width:840px;width:92%}.site-navigation{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:40px;-moz-column-gap:40px;column-gap:40px}.site-navigation input[type="checkbox"],.site-navigation label{display:none}.site-navigation ul{list-style:none;margin:0;padding:0}.site-navigation ul li{margin-bottom:20px;font-size:22px;line-height:23px}.site-navigation ul li a{display:block;color:#444;font-weight:700;text-decoration:none}.site-navigation ul li a:hover{color:#8892bf}.site-navigation ul li ul{padding-top:8px}.site-navigation ul li li{margin-bottom:6px;font-size:18px}.site-navigation ul li li a{border:none;color:#777;font-weight:normal}.site-navigation li{-webkit-column-break-inside:avoid;page-break-inside:avoid;break-inside:avoid}@media (max-width:820px){.site-navigation{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:560px){.site-navigation{-webkit-columns:1;-moz-columns:1;columns:1}}@media (max-width:375px){.site-navigation{background:rgba(255,255,255,0.95);-webkit-columns:1;-moz-columns:1;columns:1;max-height:100vh;position:fixed;bottom:0;left:0;z-index:100}.site-navigation label{background:#4f5b93;box-sizing:border-box;display:block;height:40px;padding:0 10px;width:100vh;position:absolute;bottom:0;left:0;color:white;font-family:verdana,sans-serif;font-size:13px;line-height:40px;text-transform:uppercase;z-index:2}.site-navigation>ul{background:rgba(255,255,255,0.96);border-top:3px solid #8892bf;box-shadow:rgba(0,0,0,0.25) 0 -5px 10px;box-sizing:border-box;padding:20px;overflow:auto;-webkit-overflow-scrolling:touch;position:absolute;left:0;bottom:40px;height:50vh;width:100vh;-webkit-transform:translate(0, 100vh);-ms-transform:translate(0, 100vh);transform:translate(0, 100vh);transition:all .2s ease;z-index:1}.site-navigation input[type="checkbox"]:checked~ul{-webkit-transform:translate(0, 0);-ms-transform:translate(0, 0);transform:translate(0, 0)}}.site-content h1{padding-top:40px;position:relative}.site-content h1:after{border:1px solid #ddd;border-bottom:none;content:"";display:block;height:8px;position:absolute;left:0;top:0;width:100%}.site-content.chapters{counter-reset:chapter}.site-content.chapters h1{counter-increment:chapter;padding-top:60px}.site-content.chapters h1:before{display:inline-block;content:"Chapter " counter(chapter) ".";position:absolute;top:30px;left:50%;-webkit-transform:translateX(-50%);-ms-transform:translateX(-50%);transform:translateX(-50%);color:#999;font-size:12px;letter-spacing:1px;line-height:20px;text-transform:uppercase;text-align:center}.site-content #welcome ul{-webkit-columns:3;-moz-columns:3;columns:3;-webkit-column-gap:30px;-moz-column-gap:30px;column-gap:30px;list-style-position:inside}.site-content .back-to-top{margin-bottom:60px}@media (max-width:870px){.site-content #welcome ul{-webkit-columns:2;-moz-columns:2;columns:2}}@media (max-width:600px){.site-content #welcome ul{-webkit-columns:1;-moz-columns:1;columns:1}}.site-footer{border-top:1px solid #ccc;margin:60px auto 0 auto;padding:40px 20px;font-family:verdana,sans-serif;font-size:16px;text-align:center}.site-footer .cc-badge{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFgAAAAfCAMAAABUFvrSAAAAw1BMVEX///8AAAAAAACrsar///8oKSjR1NAODg4jHyDLz8pAPz/f399wcHBQUFBgYGDJzcjEyMN5fHkwMDC9wry4vbeAgIDw8PDBxcDO0c3M0MyUmJPGysW6v7q/v7+fn5/T1tKvtK61urSxt7C/w76zuLKhpKDk5OSRk5F2c3RQUVAbGxuts6yEhoR9fnxDREMgICDW1dXJyMirq6qvr68wLS3Pz8+Rj4+Pj4+LioqEgYJaV1i6ubmbl5meoJ1dXl06NjcZGRmWw6QEAAAAAnRSTlMMANomgjQAAAMCSURBVHjatZYJc6JAEIWznWFmOAQDguAdjUqMd0yi5vz/v2q7GTmkNusWW3kxNfJkPts3TMPVFfyIfiH3ttHwRs1623F0PYp03XHa9ebI6zRu74aDwcPDdQUBXCG3440Qq4ec91GchzqhM/J1FSEYuVguYudLASixnBM6JVPJNxqgtJts2mWHwMh1Ij6dQabZlEeKfDccDlo4xbAsA6e11KzLDoG9EXHvqVbb73Z9m+q+r4dEppLHAmomQ5k1EMmsi44CY74JV/gBU+ohWqtjzSMMY6iBjR4AfQAaTVLO87HkTDabiXIUuNnWieuaLFPgYs1cb1PJC6itUzCrwQ2mCe4bcr9EPEkdOmcsUa+Jo8B1J5wiF8s9J0/DpGQNCt9ogkbladKwwZ/DNnNMtpGfdizlMzkKjAXPQDyxMwUCZqpkMOjYBrBpNADnGDESZDxZ5w4L3uQec5A7chTYCecAPiupBzDHkr0OWHQIKBotwqCzidGI17kTSKlhzFJOyFFgvgSBQXRrhuGr4QUnCFhyzOIbMDLinZTH18y523UTsJmBdS7ARiCQjEcg2fTjBdfrzc6foqCsemwtUUbqvI43jG2lxHMyMACW6MLK7K56Lrjm46qXZNGnkE+LB5AvHjlHudtBvF3MUqcn5eGgybd88aI+AP4KlbMaSF0ERwj2ocZKlxs5k8OXeA6KzkGirICcfwI3ChvEKm6Q/bHkbLbbtXLKUQRPKx+joCGPorGttKXzxTutWrZ41mnxGrdjDcC1LTdvOZcddbndg2DZ5fZoJANbqcuNGtygWttMdvTLtxsE+1uFXp9vafO7LV0ZTE3o/S9NqBqXwLDQ+QeSC23IVG1zDtVFYLD0s0Yf+ALgk0cL+F8wLCL+Ubo18agFqdT+oDeZo/7RL53EzsGUxnvpZtoqzDm9WO6o49JXKaMIpjRCPk1v/1Me6sUc0rZZcE5/BaXtpAQGd4Bozul5BbEDAwoqB6GcrOLcLFesZOw99Yjl7Ql7oeIUXjynBP4h/djT5m+nuF33PcPucwAAAABJRU5ErkJggg==);background-position:top left;background-repeat:no-repeat;background-size:contain;display:inline-block;height:31px;width:88px}.site-footer h2{font-size:24px;font-weight:bold;line-height:30px;margin-bottom:10px}.site-footer ul{list-style:none;margin:0 0 20px 0;padding:0}.site-footer .license{color:#777;font-size:13px}
        </style>
    </head>
    <body>
        <header class="site-header">
            <h1><a href="/">PHP <em>The Right Way</em></a></h1>
            <div class="build-date">Last Updated: {{ site.time }}</div>
            <div class="share">
                <a class="btn-share" href="https://x.com/intent/tweet?text=PHP+The+Right+Way&amp;url=https%3A%2F%2Fwww.phptherightway.com&amp;hashtags=PHP" target="_blank">Share on X</a>
            </div>
            <a class="fork-me" href="https://github.com/codeguy/php-the-right-way" target="_blank"></a>
        </header>

        <div class="site-content">
            {{ content }}
        </div>

        <footer class="site-footer" id="credits">
            <h2>Created and maintained by</h2>
            <ul>
                <li><a href="https://joshlockhart.com" target="_blank">Josh Lockhart</a></li>
                <li><a href="https://philsturgeon.co.uk/" target="_blank">Phil Sturgeon</a></li>
                <li><a href="https://github.com/codeguy/php-the-right-way/graphs/contributors" target="_blank">Project Contributors</a></li>
            </ul>
            <div class="license">
                <a class="cc-badge" rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/"></a>
                <br />
                <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">PHP: The Right Way</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://joshlockhart.com" property="cc:attributionName" rel="cc:attributionURL">Josh Lockhart</a>
                <br/>
                is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://www.phptherightway.com" rel="dct:source">www.phptherightway.com</a>.
            </div>
        </footer>
    </body>
</html>


================================================
FILE: _posts/01-01-01-Getting-Started.md
================================================
---
anchor: getting_started
---

# Getting Started {#getting_started_title}



================================================
FILE: _posts/01-02-01-Use-the-Current-Stable-Version.md
================================================
---
title:   Use the Current Stable Version (8.5)
isChild: true
anchor:  use_the_current_stable_version
---

## Use the Current Stable Version (8.5) {#use_the_current_stable_version_title}

If you are getting started with PHP, start with the current stable release of [PHP 8.5][php-release]. PHP 8.x adds many [new features](#language_highlights) over the older 7.x and 5.x versions. The engine has been largely re-written, and PHP is now even quicker than older versions. PHP 8 is a major update of the language and contains many new features and optimizations.

You should try to upgrade to the latest stable version quickly - PHP 7.4 [is already End of Life][php-supported]. Upgrading is easy, as there are not many backwards compatibility breaks [PHP 8.0][php-bc-80], [PHP 8.1][php-bc-81], [PHP 8.2][php-bc-82], [PHP 8.3][php-bc-83], [PHP 8.4][php-bc-84], [PHP 8.5][php-bc-85]. If you are not sure which version a function or feature is in, you can check the PHP documentation on the [php.net][php-docs] website.

[php-release]: https://www.php.net/downloads.php
[php-supported]: https://www.php.net/supported-versions.php
[php-docs]: https://www.php.net/manual/
[php-bc-80]: https://www.php.net/manual/migration80.incompatible.php
[php-bc-81]: https://www.php.net/manual/migration81.incompatible.php
[php-bc-82]: https://www.php.net/manual/migration82.incompatible.php
[php-bc-83]: https://www.php.net/manual/migration83.incompatible.php
[php-bc-84]: https://www.php.net/manual/migration84.incompatible.php
[php-bc-85]: https://www.php.net/manual/migration85.incompatible.php

================================================
FILE: _posts/01-03-01-Built-in-Web-Server.md
================================================
---
title:   Built-in Web Server
isChild: true
anchor:  builtin_web_server
---

## Built-in web server {#builtin_web_server_title}

With PHP 5.4 or newer, you can start learning PHP without installing and configuring a full-fledged web server.
To start the server, run the following command from your terminal in your project's web root:

{% highlight console %}
> php -S localhost:8000
{% endhighlight %}

* [Learn about the built-in, command line web server][cli-server]


[cli-server]: https://www.php.net/features.commandline.webserver


================================================
FILE: _posts/01-04-01-Mac-Setup.md
================================================
---
isChild: true
anchor:  mac_setup
---

## macOS Setup {#mac_setup_title}

macOS 12 (Monterey) and later does not come prepackaged with PHP. Earlier macOS versions include PHP but are behind the latest stable release. There are multiple ways to install the latest PHP version on macOS.

### Install PHP via Homebrew

[Homebrew] is a package manager for macOS that helps you easily install PHP and various extensions. The Homebrew core repository provides "formulae" for PHP 8.1, 8.2, 8.3, 8.4 and 8.5. Install the latest version with this command:

```
brew install php
```

You can switch between Homebrew PHP versions by modifying your `PATH` variable. Alternatively, you can use [brew-php-switcher][brew-php-switcher] to switch PHP versions automatically.

You can also switch between PHP versions manually by unlinking and linking the wanted version:

```
brew unlink php
brew link --overwrite php@8.2
```

```
brew unlink php
brew link --overwrite php@8.3
```

### Install PHP via Macports

The [MacPorts] Project is an open-source community initiative to design an
easy-to-use system for compiling, installing, and upgrading either
command-line, X11 or Aqua based open-source software on the macOS operating
system.

MacPorts supports pre-compiled binaries, so you don't need to recompile every
dependency from the source tarball files, it saves your life if you don't
have any package installed on your system.

At this point, you can install `php54`, `php55`, `php56`, `php70`, `php71`, `php72`, `php73`, `php74`, `php80`, `php81`, `php82`, `php83`, or `php84` using the `port install` command, for example:

    sudo port install php74
    sudo port install php83

And you can run `select` command to switch your active PHP:

    sudo port select --set php php83

### Install PHP via phpbrew

[phpbrew] is a tool for installing and managing multiple PHP versions. This can be really useful if two different
applications/projects require different versions of PHP, and you are not using virtual machines.

### Install PHP via Liip's binary installer

Another popular option is [php-osx.liip.ch] which provides one liner installation methods for versions 5.3 through 7.3.
It doesn't overwrite the PHP binaries installed by Apple, but installs everything in a separate location (/usr/local/php5).

### Compile from Source

Another option that gives you control over the version of PHP you install, is to [compile it yourself][mac-compile].
In that case be sure to have installed either [Xcode][xcode-gcc-substitution] or Apple's substitute
["Command Line Tools for XCode"] downloadable from Apple's Developer Center.

### All-in-One Installers

The solutions listed above mainly handle PHP itself, and do not supply things like [Apache][apache], [Nginx][nginx] or a SQL server.
"All-in-one" solutions such as [MAMP][mamp-downloads] and [XAMPP][xampp] will install these other bits of software for
you and tie them all together, but ease of setup comes with a trade-off of flexibility.

[Homebrew]: https://brew.sh/
[MacPorts]: https://www.macports.org/install.php
[phpbrew]: https://github.com/phpbrew/phpbrew
[php-osx.liip.ch]: https://web.archive.org/web/20220505163210/https://php-osx.liip.ch/
[mac-compile]: https://www.php.net/install.macosx.compile
[xcode-gcc-substitution]: https://github.com/kennethreitz/osx-gcc-installer
["Command Line Tools for XCode"]: https://developer.apple.com/downloads
[apache]: https://httpd.apache.org/
[nginx]: https://www.nginx.com/
[mamp-downloads]: https://www.mamp.info/en/downloads/
[xampp]: https://www.apachefriends.org/
[brew-php-switcher]: https://github.com/philcook/brew-php-switcher


================================================
FILE: _posts/01-05-01-Windows-Setup.md
================================================
---
isChild: true
anchor:  windows_setup
---

## Windows Setup {#windows_setup_title}

You can download the binaries from [windows.php.net/download][php-downloads]. After the extraction of PHP, it is recommended to set the [PATH][windows-path] to the root of your PHP folder (where php.exe is located) so you can execute PHP from anywhere.

For learning and local development, you can use the built in webserver with PHP 5.4+ so you don't need to worry about
configuring it. If you would like an "all-in-one" which includes a full-blown webserver and MySQL too then tools such
as the [XAMPP][xampp], [EasyPHP][easyphp], [OpenServer][openserver] and [WAMP][wamp] will
help get a Windows development environment up and running fast. That said, these tools will be a little different from
production so be careful of environment differences if you are working on Windows and deploying to Linux.

If you need to run your production system on Windows, then IIS7 will give you the most stable and best performance. You
can use [phpmanager][phpmanager] (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with
FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources
there is a [dedicated area on iis.net][php-iis] for PHP.

Generally running your application on different environment in development and production can lead to strange bugs popping up when you go
live. If you are developing on Windows and deploying to Linux (or anything non-Windows) then you should consider using a [Virtual Machine](/#virtualization_title).

Chris Tankersley has a very helpful blog post on what tools he uses to do [PHP development using Windows][windows-tools].

[easyphp]: https://www.easyphp.org/
[phpmanager]: http://phpmanager.codeplex.com/
[openserver]: https://ospanel.io/
[wamp]: https://www.wampserver.com/en/
[php-downloads]: https://windows.php.net/download/
[php-iis]: https://php.iis.net/
[windows-path]: https://www.windows-commandline.com/set-path-command-line/
[windows-tools]: https://ctankersley.com/2016/11/13/developing-on-windows-2016/
[xampp]: https://www.apachefriends.org/


================================================
FILE: _posts/01-06-01-Linux-Setup.md
================================================
---
isChild: true
anchor:  linux_setup
---

## Linux Setup {#linux_setup_title}

Most GNU/Linux distributions come with PHP available from the official repositories, but those packages usually are a little behind the current stable version. There are multiple ways to get newer PHP versions on such distributions.

### Ubuntu-based distributions

On Ubuntu and Debian-based GNU/Linux distributions, for instance, the best alternatives for native packages are provided and maintained by [Ondřej Surý][Ondrej Sury Blog], through his Personal Package Archive (PPA) on Ubuntu and DPA/bikeshed on Debian. Find instructions for each of these below.

For Ubuntu distributions, the [PPA by Ondřej Surý][Ondrej Sury PPA] provides supported PHP versions along with many PECL extensions. To add this PPA to your system, perform the following steps in your terminal:

1. First, add the PPA to your system's software sources using the command:

   ```bash
   sudo add-apt-repository ppa:ondrej/php
   ```

2. After adding the PPA, update your system's package list:

   ```bash
   sudo apt update
   ```

This will ensure that your system can access and install the latest PHP packages available in the PPA.

### Debian-based distributions

For Debian-based distributions, Ondřej Surý also provides a [bikeshed][bikeshed] (Debian equivalent of a PPA). To add the bikeshed to your system and update it, follow these steps:

1. Ensure that you have root access. If not, you might need to use `sudo` for the following commands.

2. Update your system's package list:

   ```bash
   sudo apt-get update
   ```

3. Install `lsb-release`, `ca-certificates`, and `curl`:

   ```bash
   sudo apt-get -y install lsb-release ca-certificates curl
   ```

4. Download the signing key for the repository:

   ```bash
   sudo curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg
   ```

5. Add the repository to your system's software sources:

   ```bash
   sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
   ```

6. Finally, update your system's package list again:

   ```bash
   sudo apt-get update
   ```

With these steps, your system will be able to install the latest PHP packages from the bikeshed.

### RPM-based distributions

On RPM-based distributions (CentOS, Fedora, RHEL, etc.) you can use the [Remi's RPM repository][remi-repo] to install the latest PHP version or to have multiple PHP versions simultaneously available.

There is a [configuration wizard][remi-wizard] available to configure your RPM-based distribution.

All that said, you can always use containers or compile the PHP source code from scratch.

[Ondrej Sury Blog]: https://deb.sury.org/
[Ondrej Sury PPA]: https://launchpad.net/~ondrej/+archive/ubuntu/php
[bikeshed]: https://packages.sury.org/php/
[remi-repo]: https://rpms.remirepo.net/
[remi-wizard]: https://rpms.remirepo.net/wizard/


================================================
FILE: _posts/01-07-01-Common-Directory-Structure.md
================================================
---
title:   Common Directory Structure
isChild: true
anchor:  common_directory_structure
---

## Common Directory structure {#common_directory_structure_title}

A common question among those starting out with writing programs for the web is, "where do I put my stuff?" Over the years, this answer has consistently been "where the `DocumentRoot` is." Although this answer is not complete, it's a great place to start.

For security reasons, configuration files should not be accessible by a site's visitors; therefore, public scripts are kept in a public directory and private configurations and data are kept outside of that directory.

For each team, CMS, or framework one works in, a standard directory structure is used by each of those entities. However, if one is starting a project alone, knowing which filesystem structure to use can be daunting.

[Paul M. Jones] has done some fantastic research into common practices of tens of thousands of github projects in the realm of PHP. He has compiled a standard file and directory structure, the [Standard PHP Package Skeleton], based on this research. In this directory structure, `DocumentRoot` should point to `public/`, unit tests should be in the `tests/` directory, and third party libraries, as installed by [composer], belong in the `vendor/` directory. For other files and directories, abiding by the [Standard PHP Package Skeleton] will make the most sense to contributors of a project.

[Paul M. Jones]: https://paul-m-jones.com/
[Standard PHP Package Skeleton]: https://github.com/php-pds/skeleton
[Composer]: /#composer_and_packagist


================================================
FILE: _posts/02-01-01-Code-Style-Guide.md
================================================
---
anchor: code_style_guide
---

# Code Style Guide {#code_style_guide_title}

The PHP community is large and diverse, composed of innumerable libraries, frameworks, and components. It is common for
PHP developers to choose several of these and combine them into a single project. It is important that PHP code adheres
(as close as possible) to a common code style to make it easy for developers to mix and match various libraries for
their projects.

The [Framework Interop Group][fig] has proposed and approved a series of style recommendations. Not all of them relate
to code-style, but those that do are [PSR-1][psr1], [PSR-12][psr12], [PSR-4][psr4] and [PER Coding Style][per-cs]. These
recommendations are merely a set of rules that many projects like Drupal, Zend, Symfony, Laravel, CakePHP, phpBB, AWS SDK,
FuelPHP, Lithium, etc. are adopting. You can use them for your own projects, or continue to use your own
personal style.

Ideally, you should write PHP code that adheres to a known standard. This could be any combination of PSRs, or one
of the coding standards made by PEAR or Zend. This means other developers can easily read and work with your code, and
applications that implement the components can have consistency even when working with lots of third-party code.

* [Read about PSR-1][psr1]
* [Read about PSR-12][psr12]
* [Read about PSR-4][psr4]
* [Read about PER Coding Style][per-cs]
* [Read about PEAR Coding Standards][pear-cs]
* [Read about Symfony Coding Standards][symfony-cs]

You can use [PHP_CodeSniffer][phpcs] to check code against any one of these recommendations, and plugins for text
editors like [Sublime Text][st-cs] to be given real-time feedback.

You can fix the code layout automatically by using one of the following tools:

- One is the [PHP Coding Standards Fixer][phpcsfixer] which has a very well tested codebase.
- Also, the [PHP Code Beautifier and Fixer][phpcbf] tool which is included with PHP_CodeSniffer can be used to adjust your code accordingly.

And you can run phpcs manually from shell:

    phpcs -sw --standard=PSR1 file.php

It will show errors and describe how to fix them.
It can also be helpful to include the `phpcs` command in a git pre-commit hook with the `--filter=GitStaged` CLI argument.
That way, code which contain violations against the chosen standard cannot enter the repository until those
violations have been fixed.

If you have PHP_CodeSniffer, then you can fix the code layout problems reported by it, automatically, with the
[PHP Code Beautifier and Fixer][phpcbf].

    phpcbf -w --standard=PSR1 file.php

Another option is to use the [PHP Coding Standards Fixer][phpcsfixer].
It will show what kind of errors the code structure had before it fixed them.

    php-cs-fixer fix -v --rules=@PSR1 file.php

English is preferred for all symbol names and code infrastructure. Comments may be written in any language easily
readable by all current and future parties who may be working on the codebase.

Finally, a good supplementary resource for writing clean PHP code is [Clean Code PHP][cleancode].

[fig]: https://www.php-fig.org/
[psr1]: https://www.php-fig.org/psr/psr-1/
[psr12]: https://www.php-fig.org/psr/psr-12/
[psr4]: https://www.php-fig.org/psr/psr-4/
[per-cs]: https://www.php-fig.org/per/coding-style/
[pear-cs]: https://pear.php.net/manual/en/standards.php
[symfony-cs]: https://symfony.com/doc/current/contributing/code/standards.html
[phpcs]: https://github.com/PHPCSStandards/PHP_CodeSniffer
[phpcbf]: https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically
[st-cs]: https://github.com/benmatselby/sublime-phpcs
[phpcsfixer]: https://cs.symfony.com/
[cleancode]: https://github.com/jupeter/clean-code-php


================================================
FILE: _posts/03-01-01-Language-Highlights.md
================================================
---
anchor: language_highlights
---

# Language Highlights {#language_highlights_title}


================================================
FILE: _posts/03-02-01-Programming-Paradigms.md
================================================
---
isChild: true
anchor:  programming_paradigms
---

## Programming Paradigms {#programming_paradigms_title}

PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over
the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in
PHP 5.3 (2009), and traits in PHP 5.4 (2012).

### Object-oriented Programming

PHP has a very complete set of object-oriented programming features including support for classes, abstract classes,
interfaces, inheritance, constructors, cloning, exceptions, and more.

* [Read about Object-oriented PHP][oop]
* [Read about Traits][traits]

### Functional Programming

PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and
built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
other functions (a feature called _Higher-order Functions_) and functions can return other functions.

Recursion, a feature that allows a function to call itself, is supported by the language, but most PHP code
is focused on iteration.

New anonymous functions (with support for closures) are present since PHP 5.3 (2009).

PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they
can be used interchangeably with anonymous functions in almost all cases.

* Continue reading on [Functional Programming in PHP](/pages/Functional-Programming.html)
* [Read about Anonymous Functions][anonymous-functions]
* [Read about the Closure class][closure-class]
* [More details in the Closures RFC][closures-rfc]
* [Read about Callables][callables]
* [Read about dynamically invoking functions with `call_user_func_array()`][call-user-func-array]

### Meta Programming

PHP supports various forms of meta-programming through mechanisms like the Reflection API and Magic Methods. There are
many Magic Methods available like `__get()`, `__set()`, `__clone()`, `__toString()`, `__invoke()`, etc. that allow
developers to hook into class behavior. Ruby developers often say that PHP is lacking `method_missing`, but it is
available as `__call()` and `__callStatic()`.

* [Read about Magic Methods][magic-methods]
* [Read about Reflection][reflection]
* [Read about Overloading][overloading]


[oop]: https://www.php.net/language.oop5
[traits]: https://www.php.net/language.oop5.traits
[anonymous-functions]: https://www.php.net/functions.anonymous
[closure-class]: https://www.php.net/class.closure
[closures-rfc]: https://wiki.php.net/rfc/closures
[callables]: https://www.php.net/language.types.callable
[call-user-func-array]: https://www.php.net/function.call-user-func-array
[magic-methods]: https://www.php.net/language.oop5.magic
[reflection]: https://www.php.net/intro.reflection
[overloading]: https://www.php.net/language.oop5.overloading


================================================
FILE: _posts/03-03-01-Namespaces.md
================================================
---
isChild: true
anchor:  namespaces
---

## Namespaces {#namespaces_title}

As mentioned above, the PHP community has a lot of developers creating lots of code. This means that one library's PHP
code might use the same class name as another. When both libraries are used in the same namespace, they collide
and cause trouble.

_Namespaces_ solve this problem. As described in the PHP reference manual, namespaces may be compared to operating
system directories that _namespace_ files; two files with the same name may co-exist in separate directories. Likewise,
two PHP classes with the same name may co-exist in separate PHP namespaces. It's as simple as that.

It is important for you to namespace your code so that it may be used by other developers without fear of colliding
with other libraries.

One recommended way to use namespaces is outlined in [PSR-4][psr4], which aims to provide a standard file, class and
namespace convention to allow plug-and-play code.

In October 2014 the PHP-FIG deprecated the previous autoloading standard: [PSR-0][psr0]. Both PSR-0 and PSR-4 are still perfectly usable.  The latter requires PHP 5.3, so many PHP 5.2-only projects implement PSR-0.

If you're going to use an autoloader standard for a new application or package, look into PSR-4.

* [Read about Namespaces][namespaces]
* [Read about PSR-0][psr0]
* [Read about PSR-4][psr4]


[namespaces]: https://www.php.net/language.namespaces
[psr0]: https://www.php-fig.org/psr/psr-0/
[psr4]: https://www.php-fig.org/psr/psr-4/


================================================
FILE: _posts/03-04-01-Standard-PHP-Library.md
================================================
---
title:   Standard PHP Library
isChild: true
anchor:  standard_php_library
---

## Standard PHP Library {#standard_php_library_title}

The Standard PHP Library (SPL) is packaged with PHP and provides a collection of classes and interfaces. It is made up
primarily of commonly needed datastructure classes (stack, queue, heap, and so on), and iterators which can traverse
over these datastructures or your own classes which implement SPL interfaces.

* [Read about the SPL][spl]
* [SPL video course on LinkedIn.com (paid)][linkedin]


[spl]: https://www.php.net/book.spl
[linkedin]: https://www.linkedin.com/learning/learning-the-standard-php-library?trk=lynda_redirect_learning


================================================
FILE: _posts/03-05-01-Command-Line-Interface.md
================================================
---
isChild: true
anchor:  command_line_interface
---

## Command Line Interface {#command_line_interface_title}

PHP was created to write web applications, but is also useful for scripting command line interface (CLI) programs.
Command line PHP programs can help automate common tasks like testing, deployment, and application administration.

CLI PHP programs are powerful because you can use your app's code directly without having to create and secure a web
GUI for it. Just be sure **not** to put your CLI PHP scripts in your public web root!

Try running PHP from your command line:

{% highlight console %}
> php -i
{% endhighlight %}

The `-i` option will print your PHP configuration just like the [`phpinfo()`][phpinfo] function.

The `-a` option provides an interactive shell, similar to ruby's IRB or python's interactive shell. There are a number
of other useful [command line options][cli-options], too.

Let's write a simple "Hello, $name" CLI program. To try it out, create a file named `hello.php`, as below.

{% highlight php %}
<?php
if ($argc !== 2) {
    echo "Usage: php hello.php <name>" . PHP_EOL;
    exit(1);
}
$name = $argv[1];
echo "Hello, $name" . PHP_EOL;
{% endhighlight %}

PHP sets up two special variables based on the arguments your script is run with. [`$argc`][argc] is an integer
variable containing the argument *count* and [`$argv`][argv] is an array variable containing each argument's *value*.
The first argument is always the name of your PHP script file, in this case `hello.php`.

The `exit()` expression is used with a non-zero number to let the shell know that the command failed. Commonly used
exit codes can be found [here][exit-codes].

To run our script, above, from the command line:

{% highlight console %}
> php hello.php
Usage: php hello.php <name>
> php hello.php world
Hello, world
{% endhighlight %}


 * [Learn about running PHP from the command line][php-cli]

[phpinfo]: https://www.php.net/function.phpinfo
[cli-options]: https://www.php.net/features.commandline.options
[argc]: https://www.php.net/reserved.variables.argc
[argv]: https://www.php.net/reserved.variables.argv
[exit-codes]: https://www.gsp.com/cgi-bin/man.cgi?section=3&amp;topic=sysexits
[php-cli]: https://www.php.net/manual/en/features.commandline.php


================================================
FILE: _posts/03-06-01-XDebug.md
================================================
---
title:   Xdebug
isChild: true
anchor:  xdebug
---

## Xdebug {#xdebug_title}

One of the most useful tools in software development is a proper debugger. It allows you to trace the execution of your
code and monitor the contents of the stack. Xdebug, PHP's debugger, can be utilized by various IDEs to provide
Breakpoints and stack inspection. It can also allow tools like PHPUnit and KCacheGrind to perform code coverage
analysis and code profiling.

If you find yourself in a bind, willing to resort to `var_dump()`/`print_r()`, and you still can't find the solution -
maybe you need to use the debugger.

[Installing Xdebug][xdebug-install] can be tricky, but one of its most important features is "Remote Debugging" - if
you develop code locally and then test it inside a VM or on another server, Remote Debugging is the feature that you
will want to enable right away.

Traditionally, you will modify your Apache VHost or .htaccess file with these values:

{% highlight ini %}
php_value xdebug.remote_host 192.168.?.?
php_value xdebug.remote_port 9000
{% endhighlight %}

The "remote host" and "remote port" will correspond to your local computer and the port that you configure your IDE to
listen on. Then it's just a matter of putting your IDE into "listen for connections" mode, and loading the URL:

    http://your-website.example.com/index.php?XDEBUG_SESSION_START=1

Your IDE will now intercept the current state as the script executes, allowing you to set breakpoints and probe the
values in memory.

Graphical debuggers make it very easy to step through code, inspect variables, and eval code against the live runtime.
Many IDEs have built-in or plugin-based support for graphical debugging with Xdebug. MacGDBp is a free, open-source,
stand-alone Xdebug GUI for macOS.

 * [Learn more about Xdebug][xdebug-docs]
 * [Learn more about MacGDBp][macgdbp-install]


[xdebug-install]: https://xdebug.org/docs/install
[xdebug-docs]: https://xdebug.org/docs/
[macgdbp-install]: https://www.bluestatic.org/software/macgdbp/


================================================
FILE: _posts/04-01-01-Dependency-Management.md
================================================
---
anchor: dependency_management
---

# Dependency Management {#dependency_management_title}

There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use 
several of them — these are project dependencies. PHP did not have a good way to manage
these project dependencies. Even if you managed them manually, you still had to worry about autoloaders.
That is no longer an issue.

Currently there are two major package management systems for PHP - [Composer] and [PEAR]. Composer is currently
the most popular package manager for PHP, however for a long time PEAR was the primary package manager in use.
Knowing PEAR's history is a good idea, since you may still find references to it even if you never use it.

[Composer]: /#composer_and_packagist
[PEAR]: /#pear


================================================
FILE: _posts/04-02-01-Composer-and-Packagist.md
================================================
---
title:   Composer and Packagist
isChild: true
anchor:  composer_and_packagist
---

## Composer and Packagist {#composer_and_packagist_title}

Composer is the recommended dependency manager for PHP. List your project's dependencies in a `composer.json` file and,
with a few simple commands, Composer will automatically download your project's dependencies and setup autoloading for
you. Composer is analogous to NPM in the node.js world, or Bundler in the Ruby world.

There is a plethora of PHP libraries that are compatible with Composer and ready to be used in your project. These
"packages" are listed on [Packagist], the official repository for Composer-compatible PHP libraries.

### How to Install Composer

The safest way to download composer is by [following the official instructions](https://getcomposer.org/download/).
This will verify the installer is not corrupt or tampered with.
The installer installs a `composer.phar` binary in your _current working directory_.

We recommend installing Composer *globally* (e.g. a single copy in `/usr/local/bin`). To do so, run this command next:

{% highlight console %}
mv composer.phar /usr/local/bin/composer
{% endhighlight %}

**Note:** If the above fails due to permissions, prefix with `sudo`.

To run a locally installed Composer you'd use `php composer.phar`, globally it's simply `composer`.

#### Installing on Windows

For Windows users the easiest way to get up and running is to use the [ComposerSetup] installer, which
performs a global install and sets up your `$PATH` so that you can just call `composer` from any
directory in your command line.

### How to Define and Install Dependencies

Composer keeps track of your project's dependencies in a file called `composer.json`. You can manage it
by hand if you like, or use Composer itself. The `composer require` command adds a project dependency
and if you don't have a `composer.json` file, one will be created. Here's an example that adds [Twig]
as a dependency of your project.

{% highlight console %}
composer require twig/twig:^2.0
{% endhighlight %}

Alternatively, the `composer init` command will guide you through creating a full `composer.json` file
for your project. Either way, once you've created your `composer.json` file you can tell Composer to
download and install your dependencies into the `vendor/` directory. This also applies to projects
you've downloaded that already provide a `composer.json` file:

{% highlight console %}
composer install
{% endhighlight %}

Next, add this line to your application's primary PHP file; this will tell PHP to use Composer's
autoloader for your project dependencies.

{% highlight php %}
<?php
require 'vendor/autoload.php';
{% endhighlight %}

Now you can use your project dependencies, and they'll be autoloaded on demand.

### Updating your dependencies

Composer creates a file called `composer.lock` which stores the exact version of each package it
downloaded when you first ran `composer install`. If you share your project with others,
ensure the `composer.lock` file is included, so that when they run `composer install` they'll
get the same versions as you.  To update your dependencies, run `composer update`. Don't use
`composer update` when deploying, only `composer install`, otherwise you may end up with different
package versions on production.

This is most useful when you define your version requirements flexibly. For instance, a version
requirement of `~1.8` means "anything newer than `1.8.0`, but less than `2.0.x-dev`". You can also use
the `*` wildcard as in `1.8.*`. Now Composer's `composer update` command will upgrade all your
dependencies to the newest version that fits the restrictions you define.

### Update Notifications

To receive notifications about new version releases you can sign up for [libraries.io], a web service
that can monitor dependencies and send you alerts on updates.

### Checking your dependencies for security issues

The [Local PHP Security Checker] is a command-line tool, which will examine your `composer.lock`
file and tell you if you need to update any of your dependencies.

### Handling global dependencies with Composer

Composer can also handle global dependencies and their binaries. Usage is straight-forward, all you need
to do is prefix your command with `global`. If for example you wanted to install PHPUnit and have it
available globally, you'd run the following command:

{% highlight console %}
composer global require phpunit/phpunit
{% endhighlight %}

This will create a `~/.composer` folder where your global dependencies reside. To have the installed
packages' binaries available everywhere, you'd then add the `~/.composer/vendor/bin` folder to your
`$PATH` variable.

* [Learn about Composer]

[Packagist]: https://packagist.org/
[Twig]: https://twig.symfony.com/
[libraries.io]: https://libraries.io/
[Local PHP Security Checker]: https://github.com/fabpot/local-php-security-checker
[Learn about Composer]: https://getcomposer.org/doc/00-intro.md
[ComposerSetup]: https://getcomposer.org/Composer-Setup.exe


================================================
FILE: _posts/04-03-01-PEAR.md
================================================
---
title:   PEAR
isChild: true
anchor:  pear
---

## PEAR {#pear_title}

A veteran package manager that some PHP developers enjoy is [PEAR][1]. It behaves similarly to Composer,
but has some notable differences.

PEAR requires each package to have a specific structure, which means that the author of the package must prepare it for
usage with PEAR. Using a project which was not prepared to work with PEAR is not possible.

PEAR installs packages globally, which means after installing them once they are available to all projects on that
server. This can be good if many projects rely on the same package with the same version but might lead to problems if
version conflicts between two projects arise.

### How to install PEAR

You can install PEAR by downloading the `.phar` installer and executing it. The PEAR documentation has
detailed [install instructions][2] for every operating system.

If you are using Linux, you can also have a look at your distribution package manager. Debian and Ubuntu,
for example, have an apt `php-pear` package.

### How to install a package

If the package is listed on the [PEAR packages list][3], you can install it by specifying the official name:

{% highlight console %}
pear install foo
{% endhighlight %}

If the package is hosted on another channel, you need to `discover` the channel first and also specify it when
installing. See the [Using channel docs][4] for more information on this topic.

* [Learn about PEAR][1]

### Handling PEAR dependencies with Composer

If you are already using [Composer][5] and you would like to install some PEAR code too, you can use Composer to
handle your PEAR dependencies. PEAR repositories are no longer directly supported by Composer version 2, so you must manually add a repository to install PEAR packages:

{% highlight json %}
{
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "pear2/pear2-http-request",
                "version": "2.5.1",
                "dist": {
                    "url": "https://github.com/pear2/HTTP_Request/archive/refs/heads/master.zip",
                    "type": "zip"
                }
            }
        }
    ],
    "require": {
        "pear2/pear2-http-request": "*"
    },
    "autoload": {
        "psr-4": {"PEAR2\\HTTP\\": "vendor/pear2/pear2-http-request/src/HTTP/"}
    }
}
{% endhighlight %}

The first section `"repositories"` will be used to let Composer know it should "initialize" (or "discover" in PEAR
terminology) the pear repo. Then the `require` section will prefix the package name like this:

> pear-channel/package

The "pear" prefix is hardcoded to avoid any conflicts, as a pear channel could be the same as another packages vendor
name for example, then the channel short name (or full URL) can be used to reference which channel the package is in.

When this code is installed it will be available in your vendor directory and automatically available through the
Composer autoloader:

> vendor/pear2/pear2-http-request/pear2/HTTP/Request.php

To use this PEAR package simply reference it like so:

{% highlight php %}
<?php
require __DIR__ . '/vendor/autoload.php';

use PEAR2\HTTP\Request;

$request = new Request();
{% endhighlight %}

* [Learn more about using repositories with Composer][6]


[1]: https://pear.php.net/
[2]: https://pear.php.net/manual/installation.getting.php
[3]: https://pear.php.net/packages.php
[4]: https://pear.php.net/manual/guide.users.commandline.channels.php
[5]: /#composer_and_packagist
[6]: https://getcomposer.org/doc/05-repositories.md


================================================
FILE: _posts/05-01-01-Coding-Practices.md
================================================
---
anchor: coding_practices
---

# Coding Practices {#coding_practices_title}


================================================
FILE: _posts/05-02-01-The-Basics.md
================================================
---
isChild: true
anchor:  the_basics
---

## The Basics {#the_basics_title}

PHP is a vast language that allows coders of all levels the ability to produce code not only quickly, but efficiently.
However, while advancing through the language, we often forget the basics that we first learnt (or overlooked) in favor
of short cuts and/or bad habits. To help combat this common issue, this section is aimed at reminding coders of the
basic coding practices within PHP.

* Continue reading on [The Basics](/pages/The-Basics.html)

================================================
FILE: _posts/05-03-01-Date-and-Time.md
================================================
---
title:   Date and Time
isChild: true
anchor:  date_and_time
---

## Date and Time {#date_and_time_title}

PHP has a class named DateTime to help you when reading, writing, comparing or calculating with date and time. There
are many date and time related functions in PHP besides DateTime, but it provides nice object-oriented interface to
most common uses. DateTime can handle time zones, but that is outside the scope of this short introduction.

To start working with DateTime, convert raw date and time string to an object with `createFromFormat()` factory method
or do `new DateTime` to get the current date and time. Use `format()` method to convert DateTime back to a string for
output.

{% highlight php %}
<?php
$raw = '22. 11. 1968';
$start = DateTime::createFromFormat('d. m. Y', $raw);

echo 'Start date: ' . $start->format('Y-m-d') . PHP_EOL;
{% endhighlight %}

Calculating with DateTime is possible with the DateInterval class. DateTime has methods like `add()` and `sub()` that
take a DateInterval as an argument. Do not write code that expects the same number of seconds in every day. Both daylight
saving and time zone alterations will break that assumption. Use date intervals instead. To calculate date difference
use the `diff()` method. It will return new DateInterval, which is super easy to display.

{% highlight php %}
<?php
// create a copy of $start and add one month and 6 days
$end = clone $start;
$end->add(new DateInterval('P1M6D'));

$diff = $end->diff($start);
echo 'Difference: ' . $diff->format('%m month, %d days (total: %a days)') . PHP_EOL;
// Difference: 1 month, 6 days (total: 37 days)
{% endhighlight %}

You can use standard comparisons on DateTime objects:

{% highlight php %}
<?php
if ($start < $end) {
    echo "Start is before the end!" . PHP_EOL;}
{% endhighlight %}

One last example to demonstrate the DatePeriod class. It is used to iterate over recurring events. It can take two
DateTime objects, start and end, and the interval for which it will return all events in between.

{% highlight php %}
<?php
// output all thursdays between $start and $end
$periodInterval = DateInterval::createFromDateString('first thursday');
$periodIterator = new DatePeriod($start, $periodInterval, $end, DatePeriod::EXCLUDE_START_DATE);
foreach ($periodIterator as $date) {
    // output each date in the period
    echo $date->format('Y-m-d') . ' ';
}
{% endhighlight %}

A popular PHP API extension is [Carbon](https://carbon.nesbot.com/). It inherits everything in the DateTime class, so involves minimal code alterations, but extra features include Localization support, further ways to add, subtract and format a DateTime object, plus a means to test your code by simulating a date and time of your choosing.

* [Read about DateTime][datetime]
* [Read about date formatting][dateformat] (accepted date format string options)

[datetime]: https://www.php.net/book.datetime
[dateformat]: https://www.php.net/function.date


================================================
FILE: _posts/05-04-01-Design-Patterns.md
================================================
---
isChild: true
anchor:  design_patterns
---

## Design Patterns {#design_patterns_title}

When you are building your application it is helpful to use common patterns in your code and common patterns for the
overall structure of your project. Using common patterns is helpful because it makes it much easier to manage your code
and lets other developers quickly understand how everything fits together.

If you use a framework then most of the higher level code and project structure will be based on that framework, so a
lot of the pattern decisions are made for you. But it is still up to you to pick out the best patterns to follow in the
code you build on top of the framework. If, on the other hand, you are not using a framework to build your application
then you have to find the patterns that best suit the type and size of application that you're building.

You can learn more about PHP design patterns and see working examples at:

* <https://refactoring.guru/design-patterns/php>
* [https://designpatternsphp.readthedocs.io/](https://designpatternsphp.readthedocs.io/en/latest/) ([PDF download](https://www.computer-pdf.com/web-programming/php/924-tutorial-designpatternsphp-documentation.html))


================================================
FILE: _posts/05-05-01-PHP-and-UTF8.md
================================================
---
title:   Working with UTF-8
isChild: true
anchor:  php_and_utf8
---

## Working with UTF-8 {#php_and_utf8_title}

_This section was originally written by [Alex Cabal](https://alexcabal.com/) over at
[PHP Best Practices](https://phpbestpractices.org/#utf-8) and has been used as the basis for our own UTF-8 advice_.

### There's no one-liner. Be careful, detailed, and consistent.

Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK,
but it's not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We'll aim
for a brief, practical summary.

### UTF-8 at the PHP level

The basic string operations, like concatenating two strings and assigning strings to variables, don't need anything
special for UTF-8. However, most string functions, like `strpos()` and `strlen()`, do need special consideration. These
functions often have an `mb_*` counterpart: for example, `mb_strpos()` and `mb_strlen()`. These `mb_*` strings are made
available to you via the [Multibyte String Extension], and are specifically designed to operate on Unicode strings.

You must use the `mb_*` functions whenever you operate on a Unicode string. For example, if you use `substr()` on a
UTF-8 string, there's a good chance the result will include some garbled half-characters. The correct function to use
would be the multibyte counterpart, `mb_substr()`.

The hard part is remembering to use the `mb_*` functions at all times. If you forget even just once, your Unicode
string has a chance of being garbled during further processing.

Not all string functions have an `mb_*` counterpart. If there isn't one for what you want to do, then you might be out
of luck.

You should use the `mb_internal_encoding()` function at the top of every PHP script you write (or at the top of your
global include script), and the `mb_http_output()` function right after it if your script is outputting to a browser.
Explicitly defining the encoding of your strings in every script will save you a lot of headaches down the road.

Additionally, many PHP functions that operate on strings have an optional parameter letting you specify the character
encoding. You should always explicitly indicate UTF-8 when given the option. For example, `htmlentities()` has an
option for character encoding, and you should always specify UTF-8 if dealing with such strings. Note that as of PHP 5.4.0, UTF-8 is the default encoding for `htmlentities()` and `htmlspecialchars()`.

Finally, If you are building a distributed application and cannot be certain that the `mbstring` extension will be
enabled, then consider using the [symfony/polyfill-mbstring] Composer package. This will use `mbstring` if it is available, and
fall back to non UTF-8 functions if not.

[Multibyte String Extension]: https://www.php.net/book.mbstring
[symfony/polyfill-mbstring]: https://packagist.org/packages/symfony/polyfill-mbstring

### UTF-8 at the Database level

If your PHP script accesses MySQL, there's a chance your strings could be stored as non-UTF-8 strings in the database
even if you follow all of the precautions above.

To make sure your strings go from PHP to MySQL as UTF-8, make sure your database and tables are all set to the
`utf8mb4` character set and collation, and that you use the `utf8mb4` character set in the PDO connection string. See
example code below. This is _critically important_.

Note that you must use the `utf8mb4` character set for complete UTF-8 support, not the `utf8` character set! See
Further Reading for why.

### UTF-8 at the browser level

Use the `mb_http_output()` function to ensure that your PHP script outputs UTF-8 strings to your browser.

The browser will then need to be told by the HTTP response that this page should be considered as UTF-8. Today, it is common to set the character set in the HTTP response header like this:

{% highlight php %}
<?php
header('Content-Type: text/html; charset=UTF-8')
{% endhighlight %}

The historic approach to doing that was to include the [charset `<meta>` tag](http://htmlpurifier.org/docs/enduser-utf8.html) in your page's `<head>` tag.

{% highlight php %}
<?php
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding('UTF-8');
$utf_set = ini_set('default_charset', 'utf-8');
if (!$utf_set) {
    throw new Exception('could not set default_charset to utf-8, please ensure it\'s set on your system!');
}

// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output('UTF-8');
 
// Our UTF-8 test string
$string = 'Êl síla erin lû e-govaned vîn.';

// Transform the string in some way with a multibyte function
// Note how we cut the string at a non-Ascii character for demonstration purposes
$string = mb_substr($string, 0, 15);

// Connect to a database to store the transformed string
// See the PDO example in this document for more information
// Note the `charset=utf8mb4` in the Data Source Name (DSN)
$link = new PDO(
    'mysql:host=your-hostname;dbname=your-db;charset=utf8mb4',
    'your-username',
    'your-password',
    array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => false
    )
);

// Store our transformed string as UTF-8 in our database
// Your DB and tables are in the utf8mb4 character set and collation, right?
$handle = $link->prepare('insert into ElvishSentences (Id, Body, Priority) values (default, :body, :priority)');
$handle->bindParam(':body', $string, PDO::PARAM_STR);
$priority = 45;
$handle->bindParam(':priority', $priority, PDO::PARAM_INT); // explicitly tell pdo to expect an int
$handle->execute();

// Retrieve the string we just stored to prove it was stored correctly
$handle = $link->prepare('select * from ElvishSentences where Id = :id');
$id = 7;
$handle->bindParam(':id', $id, PDO::PARAM_INT);
$handle->execute();

// Store the result into an object that we'll output later in our HTML
// This object won't kill your memory because it fetches the data Just-In-Time to
$result = $handle->fetchAll(\PDO::FETCH_OBJ);

// An example wrapper to allow you to escape data to html
function escape_to_html($dirty){
    echo htmlspecialchars($dirty, ENT_QUOTES, 'UTF-8');
}

header('Content-Type: text/html; charset=UTF-8'); // Unnecessary if your default_charset is set to utf-8 already
?><!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>UTF-8 test page</title>
    </head>
    <body>
        <?php
        foreach($result as $row){
            escape_to_html($row->Body);  // This should correctly output our transformed UTF-8 string to the browser
        }
        ?>
    </body>
</html>
{% endhighlight %}

### Further reading

* [PHP Manual: String Operations](https://www.php.net/language.operators.string)
* [PHP Manual: String Functions](https://www.php.net/ref.strings)
    * [`strpos()`](https://www.php.net/function.strpos)
    * [`strlen()`](https://www.php.net/function.strlen)
    * [`substr()`](https://www.php.net/function.substr)
* [PHP Manual: Multibyte String Functions](https://www.php.net/ref.mbstring)
    * [`mb_strpos()`](https://www.php.net/function.mb-strpos)
    * [`mb_strlen()`](https://www.php.net/function.mb-strlen)
    * [`mb_substr()`](https://www.php.net/function.mb-substr)
    * [`mb_internal_encoding()`](https://www.php.net/function.mb-internal-encoding)
    * [`mb_http_output()`](https://www.php.net/function.mb-http-output)
    * [`htmlentities()`](https://www.php.net/function.htmlentities)
    * [`htmlspecialchars()`](https://www.php.net/function.htmlspecialchars)
* [Stack Overflow: What factors make PHP Unicode-incompatible?](https://stackoverflow.com/questions/571694/what-factors-make-php-unicode-incompatible)
* [Stack Overflow: Best practices in PHP and MySQL with international strings](https://stackoverflow.com/questions/140728/best-practices-in-php-and-mysql-with-international-strings)
* [How to support full Unicode in MySQL databases](https://mathiasbynens.be/notes/mysql-utf8mb4)
* [Bringing Unicode to PHP with Portable UTF-8](https://www.sitepoint.com/bringing-unicode-to-php-with-portable-utf8/)
* [Stack Overflow: DOMDocument loadHTML does not encode UTF-8 correctly](https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly)


================================================
FILE: _posts/05-06-01-Internationalization-and-Localization.md
================================================
---
title:   Internationalization and Localization
isChild: true
anchor:  i18n_l10n
---

## Internationalization (i18n) and Localization (l10n) {#i18n_l10n_title}

_Disclaimer for newcomers: i18n and l10n are numeronyms, a kind of abbreviation where numbers are used to shorten
words - in our case, internationalization becomes i18n and localization, l10n._

First of all, we need to define those two similar concepts and other related things:

- **Internationalization** is when you organize your code so it can be adapted to different languages or regions
without refactorings. This action is usually done once - preferably, at the beginning of the project, or else you will
probably need some huge changes in the source!
- **Localization** happens when you adapt the interface (mainly) by translating contents, based on the i18n work done
before. It usually is done every time a new language or region needs support and is updated when new interface pieces
are added, as they need to be available in all supported languages.
- **Pluralization** defines the rules required between distinct languages to interoperate strings containing numbers and 
counters. For instance, in English when you have only one item, it is singular, and anything different from that is 
called plural; plural in this language is indicated by adding an S after some words, and sometimes changes parts of it.
In other languages, such as Russian or Serbian, there are two plural forms in addition to the singular - you may even
find languages with a total of four, five or six forms, such as Slovenian, Irish or Arabic.

## Common ways to implement
The easiest way to internationalize PHP software is by using array files and using those strings in templates, such as
`<h1><?=$TRANS['title_about_page']?></h1>`. This way is, however, hardly recommended for serious projects, as it poses
some maintenance issues along the road - some might appear in the very beginning, such as pluralization. So, please,
don't try this if your project will contain more than a couple of pages.

The most classic way and often taken as reference for i18n and l10n is a [Unix tool called `gettext`][gettext]. It dates
back to 1995 and is still a complete implementation for translating software. It is easy enough to get running, while
still sporting powerful supporting tools. It is about Gettext we will be talking here. Also, to help you not get messy
over the command-line, we will be presenting a great GUI application that can be used to easily update your l10n source.

### Other tools

There are common libraries used that support Gettext and other implementations of i18n. Some of them may seem easier to
install or sport additional features or i18n file formats. In this document, we focus on the tools provided with the
PHP core, but here we list others for completion:

- [aura/intl][aura-intl]: Provides internationalization (I18N) tools, specifically package-oriented per-locale message
translation. It uses array formats for messages. Does not provide a message extractor, but does provide advanced
message formatting via the `intl` extension (including pluralized messages).
- [php-gettext/Gettext][php-gettext]: Gettext support with an OO interface; includes improved helper functions, powerful
extractors for several file formats (some of them not supported natively by the `gettext` command), and can also export
to other formats besides `.mo/.po` files. Can be useful if you need to integrate your translation files into other
parts of the system, like a JavaScript interface.
- [symfony/translation][symfony]: supports a lot of different formats, but recommends using verbose XLIFF's. Doesn't
include helper functions nor a built-in extractor, but supports placeholders using `strtr()` internally.
- [laminas/laminas-i18n][laminas]: supports array and INI files, or Gettext formats. Implements a caching layer to save you from
reading the filesystem every time. It also includes view helpers, and locale-aware input filters and validators.
However, it has no message extractor.

Other frameworks also include i18n modules, but those are not available outside of their codebases:

- [Laravel] supports basic array files, has no automatic extractor but includes a `@lang` helper for template files.
- [Yii] supports array, Gettext, and database-based translation, and includes a messages extractor. It is backed by the
[`Intl`][intl] extension, available since PHP 5.3, and based on the [ICU project]; this enables Yii to run powerful
replacements, like spelling out numbers, formatting dates, times, intervals, currency, and ordinals.

If you decide to go for one of the libraries that provide no extractors, you may want to use the gettext formats, so
you can use the original gettext toolchain (including Poedit) as described in the rest of the chapter.

## Gettext

### Installation
You might need to install Gettext and the related PHP library by using your package manager, like `apt-get` or `yum`.
After installed, enable it by adding `extension=gettext.so` (Linux/Unix) or `extension=php_gettext.dll` (Windows) to
your `php.ini`.

Here we will also be using [Poedit] to create translation files. You will probably find it in your system's package
manager; it is available for Unix, macOS, and Windows, and can be [downloaded for free on their website][poedit_download]
as well.

### Structure

#### Types of files
There are three files you usually deal with while working with gettext. The main ones are PO (Portable Object) and
MO (Machine Object) files, the first being a list of readable "translated objects" and the second, the corresponding
binary to be interpreted by gettext when doing localization. There's also a POT (Template) file, which simply contains
all existing keys from your source files, and can be used as a guide to generate and update all PO files. Those template
files are not mandatory: depending on the tool you are using to do l10n, you can go just fine with only PO/MO files.
You will always have one pair of PO/MO files per language and region, but only one POT per domain.

### Domains
There are some cases, in big projects, where you might need to separate translations when the same words convey 
different meaning given a context. In those cases, you split them into different _domains_. They are, basically, named
groups of POT/PO/MO files, where the filename is the said _translation domain_. Small and medium-sized projects usually,
for simplicity, use only one domain; its name is arbitrary, but we will be using "main" for our code samples.
In [Symfony] projects, for example, domains are used to separate the translation for validation messages.

#### Locale code
A locale is simply a code that identifies one version of a language. It is defined following the [ISO 639-1][639-1] and 
[ISO 3166-1 alpha-2][3166-1] specs: two lower-case letters for the language, optionally followed by an underline and two
upper-case letters identifying the country or regional code. For [rare languages][rare], three letters are used.

For some speakers, the country part may seem redundant. In fact, some languages have dialects in different
countries, such as Austrian German (`de_AT`) or Brazilian Portuguese (`pt_BR`). The second part is used to distinguish
between those dialects - when it is not present, it is taken as a "generic" or "hybrid" version of the language.

### Directory structure
To use Gettext, we will need to adhere to a specific structure of folders. First, you will need to select an arbitrary
root for your l10n files in your source repository. Inside it, you will have a folder for each needed locale, and a
fixed `LC_MESSAGES` folder that will contain all your PO/MO pairs. Example:

{% highlight console %}
<project root>
 ├─ src/
 ├─ templates/
 └─ locales/
    ├─ forum.pot
    ├─ site.pot
    ├─ de/
    │  └─ LC_MESSAGES/
    │     ├─ forum.mo
    │     ├─ forum.po
    │     ├─ site.mo
    │     └─ site.po
    ├─ es_ES/
    │  └─ LC_MESSAGES/
    │     └─ ...
    ├─ fr/
    │  └─ ...
    ├─ pt_BR/
    │  └─ ...
    └─ pt_PT/
       └─ ...
{% endhighlight %}

### Plural forms
As we said in the introduction, different languages might sport different plural rules. However, gettext saves us from
this trouble once again. When creating a new `.po` file, you will have to declare the [plural rules][plural] for that
language, and translated pieces that are plural-sensitive will have a different form for each of those rules. When
calling Gettext in code, you will have to specify the number related to the sentence, and it will work out the correct
form to use - even using string substitution if needed.

Plural rules include the number of plurals available and a boolean test with `n` that would define in which rule the
given number falls (starting the count with 0). For example:

- Japanese: `nplurals=1; plural=0` - only one rule
- English: `nplurals=2; plural=(n != 1);` - two rules, first if N is one, second rule otherwise
- Brazilian Portuguese: `nplurals=2; plural=(n > 1);` - two rules, second if N is bigger than one, first otherwise

Now that you understood the basis of how plural rules works - and if you didn't, please look at a deeper explanation
on the [LingoHub tutorial][lingohub_plurals] -, you might want to copy the ones you need from a [list][plural] instead
of writing them by hand.

When calling out Gettext to do localization on sentences with counters, you will have to provide it the
related number as well. Gettext will work out what rule should be in effect and use the correct localized version.
You will need to include in the `.po` file a different sentence for each plural rule defined.

### Sample implementation
After all that theory, let's get a little practical. Here's an excerpt of a `.po` file - don't mind with its format,
but with the overall content instead; you will learn how to edit it easily later:

{% highlight po %}
msgid ""
msgstr ""
"Language: pt_BR\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

msgid "We are now translating some strings"
msgstr "Nós estamos traduzindo algumas strings agora"

msgid "Hello %1$s! Your last visit was on %2$s"
msgstr "Olá %1$s! Sua última visita foi em %2$s"

msgid "Only one unread message"
msgid_plural "%d unread messages"
msgstr[0] "Só uma mensagem não lida"
msgstr[1] "%d mensagens não lidas"
{% endhighlight %}

The first section works like a header, having the `msgid` and `msgstr` especially empty. It describes the file encoding,
plural forms and other things that are less relevant.
The second section translates a simple string from English to
Brazilian Portuguese, and the third does the same, but leveraging string replacement from [`sprintf`][sprintf] so the
translation may contain the user name and visit date.
The last section is a sample of pluralization forms, displaying
the singular and plural version as `msgid` in English and their corresponding translations as `msgstr` 0 and 1
(following the number given by the plural rule). There, string replacement is used as well so the number can be seen
directly in the sentence, by using `%d`. The plural forms always have two `msgid` (singular and plural), so it is
advised not to use a complex language as the source of translation.

### Discussion on l10n keys
As you might have noticed, we are using as source ID the actual sentence in English. That `msgid` is the same used
throughout all your `.po` files, meaning other languages will have the same format and the same `msgid` fields but
translated `msgstr` lines.

Talking about translation keys, there are two main "schools" here:

1. _`msgid` as a real sentence_.
    The main advantages are:
    - if there are pieces of the software untranslated in any given language, the key displayed will still maintain some
    meaning. Example: if you happen to translate by heart from English to Spanish but need help to translate to French,
    you might publish the new page with missing French sentences, and parts of the website would be displayed in English
    instead;
    - it is much easier for the translator to understand what's going on and do a proper translation based on the
    `msgid`;
    - it gives you "free" l10n for one language - the source one;
    - The only disadvantage: if you need to change the actual text, you would need to replace the same `msgid`
    across several language files.

2. _`msgid` as a unique, structured key_.
It would describe the sentence role in the application in a structured way, including the template or part where the
string is located instead of its content.
    - it is a great way to have the code organized, separating the text content from the template logic.
    - however, that could bring problems to the translator that would miss the context. A source language file would be
    needed as a basis for other translations. Example: the developer would ideally have an `en.po` file, that
    translators would read to understand what to write in `fr.po` for instance.
    - missing translations would display meaningless keys on screen (`top_menu.welcome` instead of `Hello there, User!`
    on the said untranslated French page). That is good it as would force translation to be complete before publishing -
    however, bad as translation issues would be remarkably awful in the interface. Some libraries, though, include an
    option to specify a given language as "fallback", having a similar behavior as the other approach.

The [Gettext manual][manual] favors the first approach as, in general, it is easier for translators and users in
case of trouble. That is how we will be working here as well. However, the [Symfony documentation][symfony-keys] favors
keyword-based translation, to allow for independent changes of all translations without affecting templates as well.

### Everyday usage
In a typical application, you would use some Gettext functions while writing static text in your pages. Those sentences
would then appear in `.po` files, get translated, compiled into `.mo` files and then, used by Gettext when rendering
the actual interface. Given that, let's tie together what we have discussed so far in a step-by-step example:

#### 1. A sample template file, including some different gettext calls
{% highlight php %}
<?php include 'i18n_setup.php' ?>
<div id="header">
    <h1><?=sprintf(gettext('Welcome, %s!'), $name)?></h1>
    <!-- code indented this way only for legibility -->
    <?php if ($unread): ?>
        <h2><?=sprintf(
            ngettext('Only one unread message',
                     '%d unread messages',
                     $unread),
            $unread)?>
        </h2>
    <?php endif ?>
</div>

<h1><?=gettext('Introduction')?></h1>
<p><?=gettext('We\'re now translating some strings')?></p>
{% endhighlight %}

- [`gettext()`][func] simply translates a `msgid` into its corresponding `msgstr` for a given language. There's also
the shorthand function `_()` that works the same way;
- [`ngettext()`][n_func] does the same but with plural rules;
- There are also [`dgettext()`][d_func] and [`dngettext()`][dn_func], that allow you to override the domain for a single
call. More on domain configuration in the next example.

#### 2. A sample setup file (`i18n_setup.php` as used above), selecting the correct locale and configuring Gettext
{% highlight php %}
<?php
/**
 * Verifies if the given $locale is supported in the project
 * @param string $locale
 * @return bool
 */
function valid($locale) {
   return in_array($locale, ['en_US', 'en', 'pt_BR', 'pt', 'es_ES', 'es']);
}

//setting the source/default locale, for informational purposes
$lang = 'en_US';

if (isset($_GET['lang']) && valid($_GET['lang'])) {
    // the locale can be changed through the query-string
    $lang = $_GET['lang'];    //you should sanitize this!
    setcookie('lang', $lang); //it's stored in a cookie so it can be reused
} elseif (isset($_COOKIE['lang']) && valid($_COOKIE['lang'])) {
    // if the cookie is present instead, let's just keep it
    $lang = $_COOKIE['lang']; //you should sanitize this!
} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // default: look for the languages the browser says the user accepts
    $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    array_walk($langs, function (&$lang) { $lang = strtr(strtok($lang, ';'), ['-' => '_']); });
    foreach ($langs as $browser_lang) {
        if (valid($browser_lang)) {
            $lang = $browser_lang;
            break;
        }
    }
}

// here we define the global system locale given the found language
putenv("LANG=$lang");

// this might be useful for date functions (LC_TIME) or money formatting (LC_MONETARY), for instance
setlocale(LC_ALL, $lang);

// this will make Gettext look for ../locales/<lang>/LC_MESSAGES/main.mo
bindtextdomain('main', '../locales');

// indicates in what encoding the file should be read
bind_textdomain_codeset('main', 'UTF-8');

// if your application has additional domains, as cited before, you should bind them here as well
bindtextdomain('forum', '../locales');
bind_textdomain_codeset('forum', 'UTF-8');

// here we indicate the default domain the gettext() calls will respond to
textdomain('main');

// this would look for the string in forum.mo instead of main.mo
// echo dgettext('forum', 'Welcome back!');
?>
{% endhighlight %}

#### 3. Preparing translation for the first run
One of the great advantages Gettext has over custom framework i18n packages is its extensive and powerful file format.
"Oh man, that’s quite hard to understand and edit by hand, a simple array would be easier!" Make no mistake,
applications like [Poedit] are here to help - _a lot_. You can get the program from [their website][poedit_download],
it’s free and available for all platforms. It’s a pretty easy tool to get used to, and a very powerful one at the same
time - using all features Gettext has available. This guide is based on PoEdit 1.8.

In the first run, you should select “File > New...” from the menu. You’ll be asked straight ahead for the language:
here you can select/filter the language you want to translate to, or use that format we mentioned before, such as
`en_US` or `pt_BR`.

Now, save the file - using that directory structure we mentioned as well. Then you should click “Extract from sources”,
and here you’ll configure various settings for the extraction and translation tasks. You’ll be able to find all those
later through “Catalog > Properties”:

- Source paths: here you must include all folders from the project where `gettext()` (and siblings) are called - this
is usually your templates/views folder(s). This is the only mandatory setting;
- Translation properties:
    - Project name and version, Team and Team’s email address: useful information that goes in the .po file header;
    - Plural forms: here go those rules we mentioned before - there’s a link in there with samples as well. You can
    leave it with the default option most of the time, as PoEdit already includes a handy database of plural rules for
    many languages.
    - Charsets: UTF-8, preferably;
    - Source code charset: set here the charset used by your codebase - probably UTF-8 as well, right?
- Source keywords: The underlying software knows how `gettext()` and similar function calls look like in several
programming languages, but you might as well create your own translation functions. It will be here you’ll add those
other methods. This will be discussed later in the “Tips” section.

After setting those points it will run a scan through your source files to find all the localization calls. After every
scan PoEdit will display a summary of what was found and what was removed from the source files. New entries will fed
empty into the translation table, and you’ll start typing in the localized versions of those strings. Save it and a .mo
file will be (re)compiled into the same folder and ta-dah: your project is internationalized.

#### 4. Translating strings
As you may have noticed before, there are two main types of localized strings: simple ones and those with plural
forms. The first ones have simply two boxes: source and localized string. The source string cannot be modified as
Gettext/Poedit do not include the powers to alter your source files - you should change the source itself and rescan
the files. Tip: you may right-click a translation line and it will hint you with the source files and lines where that
string is being used.
On the other hand, plural form strings include two boxes to show the two source strings, and tabs so you can configure
the different final forms.

Whenever you change your sources and need to update the translations, just hit Refresh and Poedit will rescan the code,
removing non-existent entries, merging the ones that changed and adding new ones. It may also try to guess some
translations, based on other ones you did. Those guesses and the changed entries will receive a "Fuzzy" marker,
indicating it needs review, appearing golden in the list. It is also useful if you have a translation team and someone
tries to write something they are not sure about: just mark Fuzzy, and someone else will review later.

Finally, it is advised to leave "View > Untranslated entries first" marked, as it will help you _a lot_ to not forget
any entry. From that menu, you can also open parts of the UI that allow you to leave contextual information for
translators if needed.

### Tips & Tricks

#### Possible caching issues
If you are running PHP as a module on Apache (`mod_php`), you might face issues with the `.mo` file being cached. It
happens the first time it is read, and then, to update it, you might need to restart the server. On Nginx and PHP5 it
usually takes only a couple of page refreshes to refresh the translation cache, and on PHP7 it is rarely needed.

#### Additional helper functions
As preferred by many people, it is easier to use `_()` instead of `gettext()`. Many custom i18n libraries from
frameworks use something similar to `t()` as well, to make translated code shorter. However, that is the only function
that sports a shortcut. You might want to add in your project some others, such as `__()` or `_n()` for `ngettext()`,
or maybe a fancy `_r()` that would join `gettext()` and `sprintf()` calls. Other libraries, such as
[php-gettext's Gettext][php-gettext] also provide helper functions like these.

In those cases, you'll need to instruct the Gettext utility on how to extract the strings from those new functions.
Don't be afraid; it is very easy. It is just a field in the `.po` file, or a Settings screen on Poedit. In the editor,
that option is inside "Catalog > Properties > Source keywords". Remember: Gettext already knows the default functions
for many languages, so don’t be afraid if that list seems empty. You need to include there the specifications of those
new functions, following [a specific format][func_format]:

- if you create something like `t()` that simply returns the translation for a string, you can specify it as `t`.
Gettext will know the only function argument is the string to be translated;
- if the function has more than one argument, you can specify in which one the first string is - and if needed, the
plural form as well. For instance, if we call our function like this: `__('one user', '%d users', $number)`, the
specification would be `__:1,2`, meaning the first form is the first argument, and the second form is the second
argument. If your number comes as the first argument instead, the spec would be `__:2,3`, indicating the first form is
the second argument, and so on.

After including those new rules in the `.po` file, a new scan will bring in your new strings just as easy as before.

### References

* [Wikipedia: i18n and l10n](https://en.wikipedia.org/wiki/Internationalization_and_localization)
* [Wikipedia: Gettext](https://en.wikipedia.org/wiki/Gettext)
* [LingoHub: PHP internationalization with gettext tutorial][lingohub]
* [PHP Manual: Gettext](https://www.php.net/manual/book.gettext.php)
* [Gettext Manual][manual]

[Poedit]: https://poedit.net
[poedit_download]: https://poedit.net/download
[lingohub]: https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/
[lingohub_plurals]: https://lingohub.com/blog/2013/07/php-internationalization-with-gettext-tutorial/#Plurals
[plural]: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
[gettext]: https://en.wikipedia.org/wiki/Gettext
[manual]: https://www.gnu.org/software/gettext/manual/gettext.html
[639-1]: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
[3166-1]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
[rare]: https://www.gnu.org/software/gettext/manual/gettext.html#Rare-Language-Codes
[func_format]: https://www.gnu.org/software/gettext/manual/gettext.html#Language-specific-options
[aura-intl]: https://github.com/auraphp/Aura.Intl
[php-gettext]: https://github.com/php-gettext/Gettext
[symfony]: https://symfony.com/components/Translation
[laminas]: https://docs.laminas.dev/laminas-i18n/
[laravel]: https://laravel.com/docs/master/localization
[yii]: https://www.yiiframework.com/doc/guide/2.0/en/tutorial-i18n
[intl]: https://www.php.net/manual/intro.intl.php
[ICU project]: https://icu.unicode.org/
[symfony-keys]: https://symfony.com/doc/current/translation.html#using-real-or-keyword-messages

[sprintf]: https://www.php.net/manual/function.sprintf.php
[func]: https://www.php.net/manual/function.gettext.php
[n_func]: https://www.php.net/manual/function.ngettext.php
[d_func]: https://www.php.net/manual/function.dgettext.php
[dn_func]: https://www.php.net/manual/function.dngettext.php


================================================
FILE: _posts/06-01-01-Dependency-Injection.md
================================================
---
title:  Dependency Injection
anchor: dependency_injection
---

# Dependency Injection {#dependency_injection_title}

From [Wikipedia](https://wikipedia.org/wiki/Dependency_injection):

> Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it
> possible to change them, whether at run-time or compile-time.

This quote makes the concept sound much more complicated than it actually is. Dependency Injection is providing a
component with its dependencies either through constructor injection, method calls or the setting of properties. It is
that simple.


================================================
FILE: _posts/06-02-01-Basic-Concept.md
================================================
---
isChild: true
anchor:  basic_concept
---

## Basic Concept {#basic_concept_title}

We can demonstrate the concept with a simple, yet naive example.

Here we have a `Database` class that requires an adapter to speak to the database. We instantiate the adapter in the
constructor and create a hard dependency. This makes testing difficult and means the `Database` class is very tightly
coupled to the adapter.

{% highlight php %}
<?php
namespace Database;

class Database
{
    protected $adapter;

    public function __construct()
    {
        $this->adapter = new MySqlAdapter;
    }
}

class MysqlAdapter {}
{% endhighlight %}

This code can be refactored to use Dependency Injection and therefore loosen the dependency.
Here, we inject the dependency in a constructor and use the [constructor property promotion][php-constructor-promotion] so it is available as a property across the class:

{% highlight php %}
<?php
namespace Database;

class Database
{
    public function __construct(protected MySqlAdapter $adapter)
    {
    }
}

class MysqlAdapter {}
{% endhighlight %}

Now we are giving the `Database` class its dependency rather than creating it itself. We could even create a method
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we
could set it directly.

[php-constructor-promotion]: https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion


================================================
FILE: _posts/06-03-01-Complex-Problem.md
================================================
---
isChild: true
anchor:  complex_problem
---

## Complex Problem {#complex_problem_title}

If you have ever read about Dependency Injection then you have probably seen the terms *"Inversion of Control"* or
*"Dependency Inversion Principle"*. These are the complex problems that Dependency Injection solves.

### Inversion of Control

Inversion of Control is as it says, "inverting the control" of a system by keeping organizational control entirely
separate from our objects. In terms of Dependency Injection, this means loosening our dependencies by controlling and
instantiating them elsewhere in the system.

For years, PHP frameworks have been achieving Inversion of Control, however, the question became, which part of control
are we inverting, and where to? For example, MVC frameworks would generally provide a super object or base controller
that other controllers must extend to gain access to its dependencies. This **is** Inversion of Control, however,
instead of loosening dependencies, this method simply moved them.

Dependency Injection allows us to more elegantly solve this problem by only injecting the dependencies we need, when we
need them, without the need for any hard coded dependencies at all.

### S.O.L.I.D.

#### Single Responsibility Principle

The Single Responsibility Principle is about actors and high-level architecture. It states that “A class should have
only one reason to change.” This means that every class should _only_ have responsibility over a single part of the
functionality provided by the software. The largest benefit of this approach is that it enables improved code
_reusability_. By designing our class to do just one thing, we can use (or re-use) it in any other program without
changing it.

#### Open/Closed Principle

The Open/Closed Principle is about class design and feature extensions. It states that “Software entities (classes,
modules, functions, etc.) should be open for extension, but closed for modification.” This means that we should design
our modules, classes and functions in a way that when a new functionality is needed, we should not modify our existing
code but rather write new code that will be used by existing code. Practically speaking, this means that we should write
classes that implement and adhere to _interfaces_, then type-hint against those interfaces instead of specific classes.

The largest benefit of this approach is that we can very easily extend our code with support for something new without
having to modify existing code, meaning that we can reduce QA time, and the risk for negative impact to the application
is substantially reduced. We can deploy new code, faster, and with more confidence.

#### Liskov Substitution Principle

The Liskov Substitution Principle is about subtyping and inheritance. It states that “Child classes should never break
the parent class’ type definitions.” Or, in Robert C. Martin’s words, “Subtypes must be substitutable for their base
types.”

For example, if we have a `FileInterface` interface which defines an `embed()` method, and we have `Audio` and `Video`
classes which both implement the `FileInterface` interface, then we can expect that the usage of the `embed()` method will always
do the thing that we intend. If we later create a `PDF` class or a `Gist` class which implement the `FileInterface`
interface, we will already know and understand what the `embed()` method will do. The largest benefit of this approach
is that we have the ability to build flexible and easily-configurable programs, because when we change one object of a
type (e.g., `FileInterface`) to another we don't need to change anything else in our program.

#### Interface Segregation Principle

The Interface Segregation Principle (ISP) is about _business-logic-to-clients_ communication. It states that “No client
should be forced to depend on methods it does not use.” This means that instead of having a single monolithic interface
that all conforming classes need to implement, we should instead provide a set of smaller, concept-specific interfaces
that a conforming class implements one or more of.

For example, a `Car` or `Bus` class would be interested in a `steeringWheel()` method, but a `Motorcycle` or `Tricycle`
class would not. Conversely, a `Motorcycle` or `Tricycle` class would be interested in a `handlebars()` method, but a
`Car` or `Bus` class would not. There is no need to have all of these types of vehicles implement support for both
`steeringWheel()` as well as `handlebars()`, so we should break-apart the source interface.

#### Dependency Inversion Principle

The Dependency Inversion Principle is about removing hard-links between discrete classes so that new functionality can
be leveraged by passing a different class. It states that one should *"Depend on Abstractions. Do not depend on
concretions."*. Put simply, this means our dependencies should be interfaces/contracts or abstract classes rather than
concrete implementations. We can easily refactor the above example to follow this principle.

{% highlight php %}
<?php
namespace Database;

class Database
{
    public function __construct(protected AdapterInterface $adapter)
    {
    }
}

interface AdapterInterface {}

class MysqlAdapter implements AdapterInterface {}
{% endhighlight %}

There are several benefits to the `Database` class now depending on an interface rather than a concretion.

Consider that we are working in a team and the adapter is being worked on by a colleague. In our first example, we
would have to wait for said colleague to finish the adapter before we could properly mock it for our unit tests. Now
that the dependency is an interface/contract we can happily mock that interface knowing that our colleague will build
the adapter based on that contract.

An even bigger benefit to this method is that our code is now much more scalable. If a year down the line we decide
that we want to migrate to a different type of database, we can write an adapter that implements the original interface
and injects that instead, no more refactoring would be required as we can ensure that the adapter follows the contract
set by the interface.


================================================
FILE: _posts/06-04-01-Containers.md
================================================
---
isChild: true
anchor:  containers
---

## Containers {#containers_title}

The first thing you should understand about Dependency Injection Containers is that they are not the same thing as
Dependency Injection. A container is a convenience utility that helps us implement Dependency Injection, however, they
can be and often are misused to implement an anti-pattern, Service Location. Injecting a DI container as a Service
Locator in to your classes arguably creates a harder dependency on the container than the dependency you are replacing.
It also makes your code much less transparent and ultimately harder to test.

Most modern frameworks have their own Dependency Injection Container that allows you to wire your dependencies together
through configuration. What this means in practice is that you can write application code that is as clean and
de-coupled as the framework it is built on.


================================================
FILE: _posts/06-05-01-Further-Reading.md
================================================
---
isChild: true
anchor:  further_reading
---

## Further Reading {#further_reading_title}

* [What is Dependency Injection?](http://fabien.potencier.org/what-is-dependency-injection.html)
* [Dependency Injection: An analogy](https://mwop.net/blog/260-Dependency-Injection-An-analogy.html)
* [Dependency Injection: Huh?](https://code.tutsplus.com/tutorials/dependency-injection-huh--net-26903)
* [Dependency Injection as a tool for testing](https://medium.com/philipobenito/dependency-injection-as-a-tool-for-testing-902c21c147f1)


================================================
FILE: _posts/07-01-01-Databases.md
================================================
---
title:  Databases
anchor: databases
---

# Databases {#databases_title}

Many times your PHP code will use a database to persist information. You have a few options to connect and interact
with your database. The recommended option **until PHP 5.1.0** was to use native drivers such as [mysqli], [pgsql],
[mssql], etc.

Native drivers are great if you are only using _one_ database in your application, but if, for example, you are using
MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the
same drivers. You'll need to learn a brand new API for each database &mdash; and that can get silly.


[mysqli]: https://www.php.net/mysqli
[pgsql]: https://www.php.net/pgsql
[mssql]: https://www.php.net/mssql


================================================
FILE: _posts/07-02-01-Databases_MySQL.md
================================================
---
isChild: true
title:   MySQL Extension
anchor:  mysql_extension
---

## MySQL Extension {#mysql_extension_title}

The [mysql] extension for PHP is incredibly old and has been superseded by two other extensions:

- [mysqli]
- [pdo]

Not only did development stop long ago on [mysql], but it
**has been [officially removed in PHP 7.0][mysql_removed]**.

To save digging into your `php.ini` settings to see which module you are using, one option is to search for `mysql_*`
in your editor of choice. If any functions such as `mysql_connect()` and `mysql_query()` show up, then `mysql` is
in use.

Even if you are not using PHP 7.x or later yet, failing to consider this upgrade as soon as possible will lead to greater
hardship when the PHP upgrade does come about. The best option is to replace mysql usage with [mysqli] or [PDO] in
your applications within your own development schedules so you won't be rushed later on.

**If you are upgrading from [mysql] to [mysqli], beware lazy upgrade guides that suggest you can simply find and replace `mysql_*` with `mysqli_*`. Not only is that a gross oversimplification, it misses out on the advantages that mysqli provides, such as parameter binding, which is also offered in [PDO][pdo].**

* [MySQLi Prepared Statements][mysqli_prepared_statements]
* [PHP: Choosing an API for MySQL][mysql_api]

[mysql]: https://www.php.net/mysqli
[mysql_removed]: https://www.php.net/manual/migration70.removed-exts-sapis.php
[mysqli]: https://www.php.net/mysqli
[pdo]: https://www.php.net/pdo
[mysql_api]: https://www.php.net/mysqlinfo.api.choosing
[mysqli_prepared_statements]: https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection


================================================
FILE: _posts/07-03-01-Databases_PDO.md
================================================
---
isChild: true
title:   PDO Extension
anchor:  pdo_extension
---

## PDO Extension {#pdo_extension_title}

[PDO] is a database connection abstraction library &mdash; built into PHP since 5.1.0 &mdash; that provides a common
interface to talk with many different databases. For example, you can use basically identical code to interface with
MySQL or SQLite:

{% highlight php %}
<?php
// PDO + MySQL
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);

// PDO + SQLite
$pdo = new PDO('sqlite:/path/db/foo.sqlite');
$statement = $pdo->query("SELECT some_field FROM some_table");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['some_field']);
{% endhighlight %}

PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of
database with the same API.

More importantly, `PDO` allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying
about database SQL injection attacks.
This is possible using PDO statements and bound parameters.

Let's assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record
from a database. This is the `wrong` way to do this:

{% highlight php %}
<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!
{% endhighlight %}

This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a
heartbeat, using a practice called [SQL Injection]. Just imagine if a hacker passes in an inventive `id` parameter by
calling a URL like `http://domain.com/?id=1%3BDELETE+FROM+users`. This will set the `$_GET['id']` variable to `1;DELETE
FROM users` which will delete all of your users! Instead, you should sanitize the ID input using PDO bound parameters.

{% highlight php %}
<?php
$pdo = new PDO('sqlite:/path/db/users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); // <-- filter your data first (see [Data Filtering](#data_filtering)), especially important for INSERT, UPDATE, etc.
$stmt->bindParam(':id', $id, PDO::PARAM_INT); // <-- Automatically sanitized for SQL by PDO
$stmt->execute();
{% endhighlight %}

This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is
introduced to the database preventing potential SQL injection attacks.

For writes, such as INSERT or UPDATE, it's especially critical to still [filter your data](#data_filtering) first and sanitize it for other things (removal of HTML tags, JavaScript, etc).  PDO will only sanitize it for SQL, not for your application.

* [Learn about PDO][pdo]

You should also be aware that database connections use up resources and it was not unheard-of to have resources
exhausted if connections were not implicitly closed, however this was more common in other languages. Using PDO you can
implicitly close the connection by destroying the object by ensuring all remaining references to it are deleted, i.e.
set to NULL. If you don't do this explicitly, PHP will automatically close the connection when your script ends -
unless of course you are using persistent connections.

* [Learn about PDO connections]


[pdo]: https://www.php.net/pdo
[SQL Injection]: https://web.archive.org/web/20210413233627/http://wiki.hashphp.org/Validation
[Learn about PDO connections]: https://www.php.net/pdo.connections


================================================
FILE: _posts/07-04-01-Interacting-via-Code.md
================================================
---
isChild: true
title:   Interacting with Databases
anchor:  databases_interacting
---

## Interacting with Databases {#databases_interacting_title}

When developers first start to learn PHP, they often end up mixing their database interaction up with their
presentation logic, using code that might look like this:

{% highlight php %}
<ul>
<?php
foreach ($db->query('SELECT * FROM table') as $row) {
    echo "<li>".$row['field1']." - ".$row['field1']."</li>";
}
?>
</ul>
{% endhighlight %}

This is bad practice for all sorts of reasons, mainly that it's hard to debug, hard to test, hard to read and it is
going to output a lot of fields if you don't put a limit on there.

While there are many other solutions to doing this - depending on if you prefer [OOP](/#object-oriented-programming) or
[functional programming](/#functional-programming) - there must be some element of separation.

Consider the most basic step:

{% highlight php %}
<?php
function getAllFoos($db) {
    return $db->query('SELECT * FROM table');
}

$results = getAllFoos($db);
foreach ($results as $row) {
    echo "<li>".$row['field1']." - ".$row['field1']."</li>"; // BAD!!
}
{% endhighlight %}

That is a good start. Put those two items in two different files and you've got some clean separation.

Create a class to place that method in and you have a "Model". Create a simple `.php` file to put the presentation
logic in and you have a "View", which is very nearly [MVC] - a common OOP architecture for most
[frameworks](/#frameworks).

**foo.php**

{% highlight php %}
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');

// Make your model available
include 'models/FooModel.php';

// Create an instance
$fooModel = new FooModel($db);
// Get the list of Foos
$fooList = $fooModel->getAllFoos();

// Show the view
include 'views/foo-list.php';
{% endhighlight %}


**models/FooModel.php**

{% highlight php %}
<?php
class FooModel
{
    public function __construct(protected PDO $db)
    {
    }

    public function getAllFoos() {
        return $this->db->query('SELECT * FROM table');
    }
}
{% endhighlight %}

**views/foo-list.php**

{% highlight php %}
<?php foreach ($fooList as $row): ?>
    <li><?= $row['field1'] ?> - <?= $row['field1'] ?></li>
<?php endforeach ?>
{% endhighlight %}

This is essentially the same as what most modern frameworks are doing, albeit a little more manual. You might not
need to do all of that every time, but mixing together too much presentation logic and database interaction can be a
real problem if you ever want to [unit-test](/#unit-testing) your application.


[MVC]: https://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488


================================================
FILE: _posts/07-05-01-Abstraction-Layers.md
================================================
---
isChild: true
title:   Abstraction Layers
anchor:  databases_abstraction_layers
---

## Abstraction Layers {#databases_abstraction_layers_title}

Many frameworks provide their own abstraction layer which may or may not sit on top of [PDO][1]. These will often
emulate features for one database system that is missing from another by wrapping your queries in PHP methods, giving
you actual database abstraction instead of just the connection abstraction that PDO provides. This will of course add a
little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite
then a little overhead will be worth it for the sake of code cleanliness.

Some abstraction layers have been built using the [PSR-0][psr0] or [PSR-4][psr4] namespace standards so can be
installed in any application you like:

* [Atlas][5]
* [Aura SQL][6]
* [Doctrine2 DBAL][2]
* [Medoo][8]
* [Propel][7]
* [laminas-db][4]


[1]: https://www.php.net/book.pdo
[2]: https://www.doctrine-project.org/projects/dbal.html
[4]: https://docs.laminas.dev/laminas-db/
[5]: https://atlasphp.io
[6]: https://github.com/auraphp/Aura.Sql
[7]: https://propelorm.org/
[8]: https://medoo.in/
[psr0]: https://www.php-fig.org/psr/psr-0/
[psr4]: https://www.php-fig.org/psr/psr-4/


================================================
FILE: _posts/08-01-01-Templating.md
================================================
---
title:  Templating
anchor: templating
---

# Templating {#templating_title}

Templates provide a convenient way of separating your controller and domain logic from your presentation logic.
Templates typically contain the HTML of your application, but may also be used for other formats, such as XML.
Templates are often referred to as "views", which make up **part of** the second component of the
[model–view–controller](/pages/Design-Patterns.html#model-view-controller) (MVC) software architecture pattern.

================================================
FILE: _posts/08-02-01-Benefits.md
================================================
---
isChild: true
anchor:  templating_benefits
---

## Benefits {#templating_benefits_title}

The main benefit to using templates is the clear separation they create between the presentation logic and the rest of
your application. Templates have the sole responsibility of displaying formatted content. They are not responsible for
data lookup, persistence or other more complex tasks. This leads to cleaner, more readable code which is especially
helpful in a team environment where developers work on the server-side code (controllers, models) and designers work on
the client-side code (markup).

Templates also improve the organization of presentation code. Templates are typically placed in a "views" folder, each
defined within a single file. This approach encourages code reuse where larger blocks of code are broken into smaller,
reusable pieces, often called partials. For example, your site header and footer can each be defined as templates,
which are then included before and after each page template.

Finally, depending on the library you use, templates can offer more security by automatically escaping user-generated
content. Some libraries even offer sand-boxing, where template designers are only given access to white-listed
variables and functions.

================================================
FILE: _posts/08-03-01-Plain-PHP-Templates.md
================================================
---
title: Plain PHP Templates
isChild: true
anchor:  plain_php_templates
---

## Plain PHP Templates {#plain_php_templates_title}

Plain PHP templates are simply templates that use native PHP code. They are a natural choice since PHP is actually a
template language itself. That simply means that you can combine PHP code within other code, like HTML. This is
beneficial to PHP developers as there is no new syntax to learn, they know the functions available to them, and their
code editors already have PHP syntax highlighting and auto-completion built-in. Further, plain PHP templates tend to be
very fast as no compiling stage is required.

Every modern PHP framework employs some kind of template system, most of which use plain PHP by default. Outside of
frameworks, libraries like [Plates][plates] or [Aura.View][aura] make working with plain PHP templates easier by
offering modern template functionality such as inheritance, layouts and extensions.

### Simple example of a plain PHP template

Using the [Plates][plates] library.

{% highlight php %}
<?php // user_profile.php ?>

<?php $this->insert('header', ['title' => 'User Profile']) ?>

<h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p>

<?php $this->insert('footer') ?>
{% endhighlight %}

### Example of plain PHP templates using inheritance

Using the [Plates][plates] library.

{% highlight php %}
<?php // template.php ?>

<html>
<head>
    <title><?=$title?></title>
</head>
<body>

<main>
    <?=$this->section('content')?>
</main>

</body>
</html>
{% endhighlight %}

{% highlight php %}
<?php // user_profile.php ?>

<?php $this->layout('template', ['title' => 'User Profile']) ?>

<h1>User Profile</h1>
<p>Hello, <?=$this->escape($name)?></p>
{% endhighlight %}


[plates]: https://platesphp.com/
[aura]: https://github.com/auraphp/Aura.View


================================================
FILE: _posts/08-04-01-Compiled-Templates.md
================================================
---
isChild: true
anchor:  compiled_templates
---

## Compiled Templates {#compiled_templates_title}

While PHP has evolved into a mature, object oriented language, it [hasn't improved much][article_templating_engines] as
a templating language. Compiled templates, like [Twig], [Brainy], or [Smarty]*, fill this void by offering a new syntax that has
been geared specifically to templating. From automatic escaping, to inheritance and simplified control structures,
compiled templates are designed to be easier to write, cleaner to read and safer to use. Compiled templates can even be
shared across different languages, [Mustache] being a good example of this. Since these templates must be compiled
there is a slight performance hit, however this is very minimal when proper caching is used.

**While Smarty offers automatic escaping, this feature is NOT enabled by default.*

### Simple example of a compiled template

Using the [Twig] library.

{% highlight html+jinja %}
{% raw %}
{% include 'header.html' with {'title': 'User Profile'} %}

<h1>User Profile</h1>
<p>Hello, {{ name }}</p>

{% include 'footer.html' %}
{% endraw %}
{% endhighlight %}

### Example of compiled templates using inheritance

Using the [Twig] library.

{% highlight html+jinja %}
{% raw %}
// template.html

<html>
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>

<main>
    {% block content %}{% endblock %}
</main>

</body>
</html>
{% endraw %}
{% endhighlight %}

{% highlight html+jinja %}
{% raw %}
// user_profile.html

{% extends "template.html" %}

{% block title %}User Profile{% endblock %}
{% block content %}
    <h1>User Profile</h1>
    <p>Hello, {{ name }}</p>
{% endblock %}
{% endraw %}
{% endhighlight %}


[article_templating_engines]: http://fabien.potencier.org/templating-engines-in-php.html
[Twig]: https://twig.symfony.com/
[Brainy]: https://github.com/box/brainy
[Smarty]: https://www.smarty.net/
[Mustache]: https://mustache.github.io/


================================================
FILE: _posts/08-05-01-Further-Reading.md
================================================
---
isChild: true
anchor:  templating_further_reading
---

## Further Reading {#templating_further_reading_title}

### Articles & Tutorials

* [Templating Engines in PHP](http://fabien.potencier.org/templating-engines-in-php.html)
* [An Introduction to Views & Templating in CodeIgniter](https://code.tutsplus.com/tutorials/an-introduction-to-views-templating-in-codeigniter--net-25648)
* [Getting Started With PHP Templating](https://www.smashingmagazine.com/2011/10/getting-started-with-php-templating/)
* [Roll Your Own Templating System in PHP](https://code.tutsplus.com/tutorials/roll-your-own-templating-system-in-php--net-16596)
* [Master Pages](https://laracasts.com/series/laravel-from-scratch/episodes/7)
* [Working With Templates in Symfony 2](https://code.tutsplus.com/tutorials/working-with-templates-in-symfony-2--cms-21172)
* [Writing Safer Templates](https://github.com/box/brainy/wiki/Writing-Safe-Templates)

### Libraries

* [Aura.View](https://github.com/auraphp/Aura.View) *(native)*
* [Blade](https://laravel.com/docs/blade) *(compiled, framework specific)*
* [Brainy](https://github.com/box/brainy) *(compiled)*
* [Latte](https://github.com/nette/latte) *(compiled)*
* [Mustache](https://github.com/bobthecow/mustache.php) *(compiled)*
* [PHPTAL](https://phptal.org/) *(compiled)*
* [Plates](https://platesphp.com/) *(native)*
* [Smarty](https://www.smarty.net/) *(compiled)*
* [Twig](https://twig.symfony.com/) *(compiled)*
* [laminas-view](https://docs.laminas.dev/laminas-view/) *(native, framework specific)*


================================================
FILE: _posts/09-01-01-Errors-and-Exceptions.md
================================================
---
title:  Errors and Exceptions
anchor: errors_and_exceptions
---

# Errors and Exceptions {#errors_and_exceptions_title}



================================================
FILE: _posts/09-02-01-Errors.md
================================================
---
isChild: true
anchor:  errors
---

## Errors {#errors_title}

In many "exception-heavy" programming languages, whenever anything goes wrong an exception will be thrown. This is
certainly a viable way to do things, but PHP is an "exception-light" programming language. While it does have
exceptions and more of the core is starting to use them when working with objects, most of PHP itself will try to keep
processing regardless of what happens, unless a fatal error occurs.

For example:

{% highlight console %}
$ php -a
php > echo $foo;
Notice: Undefined variable: foo in php shell code on line 1
{% endhighlight %}

This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from
"exception-heavy" languages, because referencing a missing variable in Python for example will throw an exception:

{% highlight console %}
$ python
>>> print foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
{% endhighlight %}

The only real difference is that Python will freak out over any small thing, so that developers can be super sure any
potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which
point it will throw an error and report it.

### Error Severity

PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings.
These have different levels of severity; `E_ERROR`, `E_NOTICE`, and `E_WARNING`. Errors are fatal run-time errors and
are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are
advisory messages caused by code that may or may not cause problems during the execution of the script, execution is
not halted. Warnings are non-fatal errors, execution of the script will not be halted.

Another type of error message reported at compile time are `E_STRICT` messages. These messages are used to suggest
changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP.

### Changing PHP's Error Reporting Behaviour

Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function
`error_reporting()` you can set the level of errors for the duration of the script execution by passing one of the
predefined error level constants, meaning if you only want to see Errors and Warnings - but not Notices - then you can
configure that:

{% highlight php %}
<?php
error_reporting(E_ERROR | E_WARNING);
{% endhighlight %}

You can also control whether or not errors are displayed to the screen (good for development) or hidden, and logged
(good for production). For more information on this check out the [Error Reporting][errorreport] section.

### Inline Error Suppression

You can also tell PHP to suppress specific errors with the Error Control Operator `@`. You put this operator at the
beginning of an expression, and any error that's a direct result of the expression is silenced.

{% highlight php %}
<?php
echo @$foo['bar'];
{% endhighlight %}

This will output `$foo['bar']` if it exists, but will simply return a null and print nothing if the variable `$foo` or
`'bar'` key does not exist. Without the error control operator, this expression could create a `PHP Notice: Undefined
variable: foo` or `PHP Notice: Undefined index: bar` error.

This might seem like a good idea, but there are a few undesirable tradeoffs. PHP handles expressions using an `@` in a
less performant way than expressions without an `@`. Premature optimization may be the root of all programming
arguments, but if performance is particularly important for your application/library it's important to understand the
error control operator's performance implications.

Secondly, the error control operator **completely** swallows the error. The error is not displayed, and the error is
not sent to the error log. Also, stock/production PHP systems have no way to turn off the error control operator. While
you may be correct that the error you're seeing is harmless, a different, less harmless error will be just as silent.

If there's a way to avoid the error suppression operator, you should consider it. For example, our code above could be
rewritten like this:

{% highlight php %}
<?php
// Null Coalescing Operator
echo $foo['bar'] ?? '';
{% endhighlight %}

One instance where error suppression might make sense is where `fopen()` fails to find a file to load. You could check
for the existence of the file before you try to load it, but if the file is deleted after the check and before the
`fopen()` (which might sound impossible, but it can happen) then `fopen()` will return false _and_ throw an error. This
is potentially something PHP should resolve, but is one case where error suppression might seem like the only valid
solution.

Earlier we mentioned there's no way in a stock PHP system to turn off the error control operator. However, [Xdebug] has
an `xdebug.scream` ini setting which will disable the error control operator. You can set this via your `php.ini` file
with the following.

{% highlight ini %}
xdebug.scream = On
{% endhighlight %}

You can also set this value at runtime with the `ini_set` function

{% highlight php %}
<?php
ini_set('xdebug.scream', '1')
{% endhighlight %}

This is most useful when you're debugging code and suspect an informative error is suppressed. Use scream with care,
and as a temporary debugging tool. There's lots of PHP library code that may not work with the error control operator
disabled.

* [Error Control Operators]
* [SitePoint]
* [Xdebug]

### ErrorException

PHP is perfectly capable of being an "exception-heavy" programming language, and only requires a few lines of code to
make the switch. Basically you can throw your "errors" as "exceptions" using the `ErrorException` class, which extends
the `Exception` class.

This is a common practice implemented by a large number of modern frameworks such as Symfony and Laravel. In debug
mode *(or dev mode)* both of these frameworks will display a nice and clean *stack trace*.

There are also some packages available for better error and exception handling and reporting. Like [Whoops!], which comes with the default installation of Laravel and can be used in any framework as well.

By throwing errors as exceptions in development you can handle them better than the usual result, and if you see an
exception during development you can wrap it in a catch statement with specific instructions on how to handle the
situation. Each exception you catch instantly makes your application that little bit more robust.

More information on this and details on how to use `ErrorException` with error handling can be found at
[ErrorException Class][errorexception].

* [Error Control Operators]
* [Predefined Constants for Error Handling]
* [`error_reporting()`][error_reporting]
* [Reporting][errorreport]


[errorreport]: /#error_reporting
[Xdebug]: https://xdebug.org/docs/basic
[Error Control Operators]: https://www.php.net/language.operators.errorcontrol
[SitePoint]: https://www.sitepoint.com/
[Whoops!]: https://filp.github.io/whoops/
[errorexception]: https://www.php.net/class.errorexception
[Predefined Constants for Error Handling]: https://www.php.net/errorfunc.constants
[error_reporting]: https://www.php.net/function.error-reporting


================================================
FILE: _posts/09-03-01-Exceptions.md
================================================
---
isChild: true
anchor:  exceptions
---

## Exceptions {#exceptions_title}

Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers.
Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or
a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an
exception to the screen meaning you instantly know there is a mistake.

PHP itself is fairly lax with this, and a call to `file_get_contents()` will usually just get you a `FALSE` and a
warning.
Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe
let you use a method like `$this->upload->get_error()` to see what went wrong. The problem here is that you have to go
looking for a mistake and check the docs to see what the error method is for this class, instead of having it made
extremely obvious.

Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you
stop another developer from being able to dynamically handle that error. Exceptions should be thrown to make a
developer aware of an error; they then can choose how to handle this. E.g.:

{% highlight php %}
<?php
$email = new Fuel\Email;
$email->subject('My Subject');
$email->body('How the heck are you?');
$email->to('guy@example.com', 'Some Guy');

try
{
    $email->send();
}
catch(Fuel\Email\ValidationFailedException $e)
{
    // The validation failed
}
catch(Fuel\Email\SendingFailedException $e)
{
    // The driver could not send the email
}
finally
{
    // Executed regardless of whether an exception has been thrown, and before normal execution resumes
}
{% endhighlight %}

### SPL Exceptions

The generic `Exception` class provides very little debugging context for the developer; however, to remedy this, it is
possible to create a specialized `Exception` type by sub-classing the generic `Exception` class:

{% highlight php %}
<?php
class ValidationException extends Exception {}
{% endhighlight %}

This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the
creation of a <em>lot</em> of custom Exceptions, some of which could have been avoided using the SPL Exceptions
provided in the [SPL extension][splext].

If for example you use the `__call()` Magic Method and an invalid method is requested then instead of throwing a
standard Exception which is vague, or creating a custom Exception just for that, you could just
`throw new BadMethodCallException;`.

* [Read about Exceptions][exceptions]
* [Read about SPL Exceptions][splexe]
* [Nesting Exceptions In PHP][nesting-exceptions-in-php]


[splext]: /#standard_php_library
[exceptions]: https://www.php.net/language.exceptions
[splexe]: https://www.php.net/spl.exceptions
[nesting-exceptions-in-php]: https://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/


================================================
FILE: _posts/10-01-01-Security.md
================================================
---
anchor: security
---

# Security {#security_title}

The best resource I've found on PHP security is [The 2018 Guide to Building Secure PHP Software](https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software) by
[Paragon Initiative](https://paragonie.com/).


================================================
FILE: _posts/10-02-01-Web-Application-Security.md
================================================
---
isChild: true
anchor:  web_application_security
---

## Web Application Security {#web_application_security_title}

It is very important for every PHP developer to learn [the basics of web application security][4], which can be broken
down into a handful of broad topics:

1. Code-data separation.
   * When data is executed as code, you get SQL Injection, Cross-Site Scripting, Local/Remote File Inclusion, etc.
   * When code is printed as data, you get information leaks (source code disclosure or, in the case of C programs,
     enough information to bypass [ASLR][5]).
2. Application logic.
   * Missing authentication or authorization controls.
   * Input validation.
3. Operating environment.
   * PHP versions.
   * Third party libraries.
   * The operating system.
4. Cryptography weaknesses.
   * [Weak random numbers][6].
   * [Chosen-ciphertext attacks][7].
   * [Side-channel information leaks][8].

There are bad people ready and willing to exploit your web application. It is important that you take necessary
precautions to harden your web application's security. Luckily, the fine folks at
[The Open Web Application Security Project][1] (OWASP) have compiled a comprehensive list of known security issues and
methods to protect yourself against them. This is a must read for the security-conscious developer. [Survive The Deep End: PHP Security][3] by Padraic Brady is also another good web application security guide for PHP.

* [Read the OWASP Security Guide][2]


[1]: https://www.owasp.org/
[2]: https://www.owasp.org/index.php/Guide_Table_of_Contents
[3]: https://phpsecurity.readthedocs.io/en/latest/index.html
[4]: https://paragonie.com/blog/2015/08/gentle-introduction-application-security
[5]: https://www.techtarget.com/searchsecurity/definition/address-space-layout-randomization-ASLR
[6]: https://paragonie.com/blog/2016/01/on-design-and-implementation-stealth-backdoor-for-web-applications
[7]: https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly
[8]: https://blog.ircmaxell.com/2014/11/its-all-about-time.html


================================================
FILE: _posts/10-03-01-Password-Hashing.md
================================================
---
isChild: true
anchor:  password_hashing
---

## Password Hashing {#password_hashing_title}

Eventually everyone builds a PHP application that relies on user login. Usernames and passwords are stored in a
database and later used to authenticate users upon login.

It is important that you properly [_hash_][3] passwords before storing them. Hashing and encrypting are [two very different things][7]
that often get confused.

Hashing is an irreversible, one-way function. This produces a fixed-length string that cannot be feasibly reversed.
This means you can compare a hash against another to determine if they both came from the same source string, but you
cannot determine the original string. If passwords are not hashed and your database is accessed by an unauthorized
third-party, all user accounts are now compromised.

Unlike hashing, encryption is reversible (provided you have the key). Encryption is useful in other areas, but is a poor
strategy for securely storing passwords.

Passwords should also be individually [_salted_][5] by adding a random string to each password before hashing. This prevents dictionary attacks and the use of "rainbow tables" (a reverse list of cryptographic hashes for common passwords.)

Hashing and salting are vital as often users use the same password for multiple services and password quality can be poor.

Additionally, you should use [a specialized _password hashing_ algorithm][6] rather than fast, general-purpose
cryptographic hash function (e.g. SHA256). The short list of acceptable password hashing algorithms (as of June 2018)
to use are:

* Argon2 (available in PHP 7.2 and newer)
* Scrypt
* **Bcrypt** (PHP provides this one for you; see below)
* PBKDF2 with HMAC-SHA256 or HMAC-SHA512

Fortunately, nowadays PHP makes this easy.

**Hashing passwords with `password_hash`**

In PHP 5.5 `password_hash()` was introduced. At this time it is using BCrypt, the strongest algorithm currently
supported by PHP. It will be updated in the future to support more algorithms as needed though. The `password_compat`
library was created to provide forward compatibility for PHP >= 5.3.7.

Below we hash a string, and then check the hash against a new string. Because our two source strings are different
('secret-password' vs. 'bad-password') this login will fail.

{% highlight php %}
<?php
require 'password.php';

$passwordHash = password_hash('secret-password', PASSWORD_DEFAULT);

if (password_verify('bad-password', $passwordHash)) {
    // Correct Password
} else {
    // Wrong password
}
{% endhighlight %}

`password_hash()` takes care of password salting for you. The salt is stored, along with the algorithm and "cost", as part of the hash.  `password_verify()` extracts this to determine how to check the password, so you don't need a separate database field to store your salts.

* [Learn about `password_hash()`] [1]
* [`password_compat` for PHP >= 5.3.7 && < 5.5] [2]
* [Learn about hashing in regards to cryptography] [3]
* [Learn about salts] [5]
* [PHP `password_hash()` RFC] [4]


[1]: https://www.php.net/function.password-hash
[2]: https://github.com/ircmaxell/password_compat
[3]: https://wikipedia.org/wiki/Cryptographic_hash_function
[4]: https://wiki.php.net/rfc/password_hash
[5]: https://wikipedia.org/wiki/Salt_(cryptography)
[6]: https://paragonie.com/blog/2016/02/how-safely-store-password-in-2016
[7]: https://paragonie.com/blog/2015/08/you-wouldnt-base64-a-password-cryptography-decoded



================================================
FILE: _posts/10-04-01-Data-Filtering.md
================================================
---
isChild: true
anchor:  data_filtering
---

## Data Filtering {#data_filtering_title}

Never ever (ever) trust foreign input introduced to your PHP code. Always sanitize and validate foreign input before
using it in code. The `filter_var()` and `filter_input()` functions can sanitize text and validate text formats (e.g.
email addresses).

Foreign input can be anything: `$_GET` and `$_POST` form input data, some values in the `$_SERVER` superglobal, and the
HTTP request body via `fopen('php://input', 'r')`. Remember, foreign input is not limited to form data submitted by the
user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign
input, too.

While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process,
output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted.

Data may be _filtered_ differently based on its purpose. For example, when unfiltered foreign input is passed into HTML
page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a
very dangerous attack. One way to avoid XSS is to sanitize all user-generated data before outputting it to your page by
removing HTML tags with the `strip_tags()` function or escaping characters with special meaning into their respective
HTML entities with the `htmlentities()` or `htmlspecialchars()` functions.

Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually
a bad idea), but you can use the built-in `escapeshellarg()` function to sanitize the executed command's arguments.

One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by
changing the filename to a file path. You need to remove `"/"`, `"../"`, [null bytes][6], or other characters from the
file path so it can't load hidden, non-public, or sensitive files.

* [Learn about data filtering][1]
* [Learn about `filter_var`][4]
* [Learn about `filter_input`][5]
* [Learn about handling null bytes][6]

### Sanitization

Sanitization removes (or escapes) illegal or unsafe characters from foreign input.

For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query.
When you use bound parameters with [PDO](#databases), it will sanitize the input for you.

Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very
hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting
libraries like [HTML Purifier][html-purifier] exist for this reason.

[See Sanitization Filters][2]

### Unserialization

It is dangerous to `unserialize()` data from users or other untrusted sources.  Doing so can allow malicious users to instantiate objects (with user-defined properties) whose destructors will be executed, **even if the objects themselves aren't used**.  You should therefore avoid unserializing untrusted data.

Use a safe, standard data interchange format such as JSON (via [`json_decode`][json_decode] and [`json_encode`][json_encode]) if you need to pass serialized data to the user.

### Validation

Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a
phone number, or age when processing a registration submission.

[See Validation Filters][3]


[1]: https://www.php.net/book.filter
[2]: https://www.php.net/filter.filters.sanitize
[3]: https://www.php.net/filter.filters.validate
[4]: https://www.php.net/function.filter-var
[5]: https://www.php.net/function.filter-input
[6]: https://www.php.net/security.filesystem.nullbytes
[html-purifier]: http://htmlpurifier.org/
[json_decode]: https://www.php.net/manual/function.json-decode.php
[json_encode]: https://www.php.net/manual/function.json-encode.php


================================================
FILE: _posts/10-05-01-Configuration-Files.md
================================================
---
isChild: true
anchor:  configuration_files
---

## Configuration Files {#configuration_files_title}

When creating configuration files for your applications, best practices recommend that one of the following methods be
followed:

- It is recommended that you store your configuration information where it cannot be accessed directly and pulled in
via the file system.
- If you must store your configuration files in the document root, name the files with a `.php` extension. This ensures
that, even if the script is accessed directly, it will not be output as plain text.
- Information in configuration files should be protected accordingly, either through encryption or group/user file
system permissions.
- It is a good idea to ensure that you do not commit configuration files containing sensitive information e.g. passwords or API tokens to source control.


================================================
FILE: _posts/10-06-01-Register-Globals.md
================================================
---
isChild: true
anchor:  register_globals
---

## Register Globals {#register_globals_title}

**NOTE:** As of PHP 5.4.0 the `register_globals` setting has been removed and can no longer be used. This is only
included as a warning for anyone in the process of upgrading a legacy application.

When enabled, the `register_globals` configuration setting makes several types of variables (including ones from
`$_POST`, `$_GET` and `$_REQUEST`) available in the global scope of your application. This can easily lead to security
issues as your application cannot effectively tell where the data is coming from.

For example: `$_GET['foo']` would be available via `$foo`, which can override variables that have been declared.

If you are using PHP < 5.4.0 __make sure__ that `register_globals` is __off__.


================================================
FILE: _posts/10-07-01-Error-Reporting.md
================================================
---
isChild: true
anchor:  error_reporting
---

## Error Reporting {#error_reporting_title}

Error logging can be useful in finding the problem spots in your application, but it can also expose information about
the structure of your application to the outside world. To effectively protect your application from issues that could
be caused by the output of these messages, you need to configure your server differently in development versus
production (live).

### Development

To show every possible error during **development**, configure the following settings in your `php.ini`:

{% highlight ini %}
display_errors = On
display_startup_errors = On
error_reporting = -1
log_errors = On
{% endhighlight %}

> Passing in the value `-1` will show every possible error, even when new levels and constants are added in future PHP
> versions. The `E_ALL` constant also behaves this way as of PHP 5.4. -
> [php.net](https://www.php.net/function.error-reporting)

The `E_STRICT` error level constant was introduced in 5.3.0 and is not part of `E_ALL`, however it became part of
`E_ALL` in 5.4.0. What does this mean? In terms of reporting every possible error in version 5.3 it means you must
use either `-1` or `E_ALL | E_STRICT`.

**Reporting every possible error by PHP version**

* &lt; 5.3 `-1` or `E_ALL`
* &nbsp; 5.3 `-1` or `E_ALL | E_STRICT`
* &gt; 5.3 `-1` or `E_ALL`

### Production

To hide errors on your **production** environment, configure your `php.ini` as:

{% highlight ini %}
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
{% endhighlight %}

With these settings in production, errors will still be logged to the error logs for the web server, but will not be
shown to the user. For more information on these settings, see the PHP manual:

* [error_reporting](https://www.php.net/errorfunc.configuration#ini.error-reporting)
* [display_errors](https://www.php.net/errorfunc.configuration#ini.display-errors)
* [display_startup_errors](https://www.php.net/errorfunc.configuration#ini.display-startup-errors)
* [log_errors](https://www.php.net/errorfunc.configuration#ini.log-errors)


================================================
FILE: _posts/11-01-01-Testing.md
================================================
---
anchor: testing
---

# Testing {#testing_title}

Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications.
Automated tests are a great tool for making sure your application does not break when you are making changes or adding
new functionality and should not be ignored.

There are several different types of testing tools (or frameworks) available for PHP, which use different approaches -
all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure
recent changes didn't break existing functionality.

================================================
FILE: _posts/11-02-01-Test-Driven-Development.md
================================================
---
isChild: true
anchor:  test_driven_development
---

## Test Driven Development {#test_driven_development_title}

From [Wikipedia](https://wikipedia.org/wiki/Test-driven_development):

> Test-driven development (TDD) is a software development process that relies on the repetition of a very short
> development cycle: first the developer writes a failing automated test case that defines a desired improvement or new
> function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck,
> who is credited with having developed or 'rediscovered' the technique, stated in 2003 that TDD encourages simple
> designs and inspires confidence.

There are several different types of testing that you can do for your application:

### Unit Testing

Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point
you build them all the way through the development cycle. By checking values going in and out of various functions and
methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building "mock"
classes and stubs you can verify that dependencies are correctly used for even better test coverage.

When you create a class or function you should create a unit test for each behavior it must have. At a very basic level
you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This
will help ensure that when you make changes to this class or function later on in the development cycle that the old
functionality continues to work as expected. The only alternative to this would be `var_dump()` in a test.php, which is
no way to build an application - large or small.

The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality
(i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project
which accepts pull requests then you should suggest this as a requirement.

[PHPUnit](https://phpunit.de/) is the de-facto testing framework for writing unit tests for PHP applications, but there
are several alternatives:

* [atoum](https://github.com/atoum/atoum)
* [Kahlan](https://github.com/kahlan/kahlan)
* [Peridot](https://peridot-php.github.io/)
* [Pest](https://pestphp.com/)
* [SimpleTest](https://github.com/simpletest/simpletest)

### Integration Testing

From [Wikipedia](https://wikipedia.org/wiki/Integration_testing):

> Integration testing (sometimes called Integration and Testing, abbreviated "I&T") is the phase in software testing in
> which individual software modules are combined and tested as a group. It occurs after unit testing and before
> validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger
> aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the
> integrated system ready for system testing.

Many of the same tools that can be used for unit testing can be used for integration testing as many of the same
principles are used.

### Functional Testing

Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that
actually use your application instead of just verifying that individual units of code are behaving correctly and that
individual units can speak to each other correctly. These tools typically work using real data and simulating actual
users of the application.

#### Functional Testing Tools

* [Codeception](https://codeception.com/) is a full-stack testing framework that includes acceptance testing tools
* [Cypress](https://www.cypress.io/)
* [Mink](https://mink.behat.org/)
* [Selenium](https://www.selenium.dev/)
* [Storyplayer](https://github.com/MeltwaterArchive/storyplayer) is a full-stack testing framework that includes support for creating and destroying test environments on demand


================================================
FILE: _posts/11-03-01-Behavior-Driven-Development.md
================================================
---
isChild: true
anchor:  behavior_driven_development
---

## Behavior Driven Development {#behavior_driven_development_title}

There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical
behavior of code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both
types of BDD.

With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then
be run as actual tests against your application. The framework used in PHP applications for StoryBDD is [Behat], which
is inspired by Ruby's [Cucumber] project and implements the Gherkin DSL for describing feature behavior.

With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function
or method, you are describing how that function or method should behave. PHP offers the [PHPSpec] framework for this
purpose. This framework is inspired by the [RSpec project][Rspec] for Ruby.

### BDD Links

* [Behat], the StoryBDD framework for PHP, inspired by Ruby's [Cucumber] project;
* [PHPSpec], the SpecBDD framework for PHP, inspired by Ruby's [RSpec] project;
* [Codeception] is a full-stack testing framework that uses BDD principles.


[Behat]: https://behat.org/
[Cucumber]: https://cucumber.io/
[PHPSpec]: https://phpspec.net/
[RSpec]: https://rspec.info/
[Codeception]: https://codeception.com/


================================================
FILE: _posts/11-04-01-Complementary-Testing-Tools.md
================================================
---
isChild: true
anchor:  complementary_testing_tools
---

## Complementary Testing Tools {#complementary_testing_tools_title}

Besides individual testing and behavior driven frameworks, there are also a number of generic frameworks and helper
libraries useful for any preferred approach taken.

### Tool Links

* [Selenium] is a browser automation tool which can be [integrated with PHPUnit]
* [Mockery] is a Mock Object Framework which can be integrated with [PHPUnit] or [PHPSpec]
* [Prophecy] is a highly opinionated yet very powerful and flexible PHP object mocking framework. It's integrated with
[PHPSpec] and can be used with [PHPUnit].
* [php-mock] is a library to help to mock PHP native functions.
* [Infection] is a PHP implementation of [Mutation Testing] to help to measure the effectiveness of your tests.
* [PHPUnit Polyfills] is a library that allows for creating PHPUnit cross-version compatible tests when a test suite needs to run against a range of PHPUnit versions.


[Selenium]: https://www.selenium.dev/
[integrated with PHPUnit]: https://github.com/giorgiosironi/phpunit-selenium/
[Mockery]: https://github.com/padraic/mockery
[PHPUnit]: https://phpunit.de/
[PHPSpec]: https://phpspec.net/
[Prophecy]: https://github.com/phpspec/prophecy
[php-mock]: https://github.com/php-mock/php-mock
[Infection]: https://github.com/infection/infection
[Mutation Testing]: https://en.wikipedia.org/wiki/Mutation_testing
[PHPUnit Polyfills]: https://github.com/Yoast/PHPUnit-Polyfills


================================================
FILE: _posts/12-01-01-Servers-and-Deployment.md
================================================
---
title:  Servers and Deployment
anchor: servers_and_deployment
---

# Servers and Deployment {#servers_and_deployment_title}

PHP applications can be deployed and run on production web servers in a number of ways.


================================================
FILE: _posts/12-02-01-Platform-as-a-Service.md
================================================
---
title:   Platform as a Service (PaaS)
isChild: true
anchor:  platform_as_a_service
---

## Platform as a Service (PaaS) {#platform_as_a_service_title}

PaaS provides the system and network architecture necessary to run PHP applications on the web. This means little to no
configuration for launching PHP applications or PHP frameworks.

Recently PaaS has become a popular method for deploying, hosting, and scaling PHP applications of all sizes. You can
find a list of [PHP PaaS "Platform as a Service" providers](#php_paas_providers) in our [resources section](#resources).

================================================
FILE: _posts/12-03-01-Virtual-or-Dedicated-Servers.md
================================================
---
title:   Virtual or Dedicated Servers
isChild: true
anchor:  virtual_or_dedicated_servers
---

## Virtual or Dedicated Servers {#virtual_or_dedicated_servers_title}

If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give
you complete control of your application's production environment.

### nginx and PHP-FPM

PHP, via PHP's built-in FastCGI Process Manager (FPM), pairs really nicely with [nginx], which is a lightweight,
high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is
especially important on virtual servers that don't have much memory to spare.

* [Read more on nginx][nginx]
* [Read more on PHP-FPM][phpfpm]
* [Read more on setting up nginx and PHP-FPM securely][secure-nginx-phpfpm]

### Apache and PHP

PHP and Apache have a long history together. Apache is wildly configurable and has many available
[modules][apache-modules] to extend functionality. It is a popular choice for shared servers and an easy setup for PHP
frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and
cannot handle as many visitors at the same time.

Apache has several possible configurations for running PHP. The most common and easiest to setup is the [prefork MPM]
with `mod_php`. While it isn't the most memory efficient, it is the simplest to get working and to use. This is probably
the best choice if you don't want to dig too deeply into the server administration aspects. Note that if you use
`mod_php` you MUST use the prefork MPM.

Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the
same FPM system as nginx and run the [worker MPM] or [event MPM] with mod_fastcgi or mod_fcgid. This configuration will
be significantly more memory efficient and much faster but it is more work to set up.

If you are running Apache 2.4 or later, you can use [mod_proxy_fcgi] to get great performance that is easy to setup.

* [Read more on Apache][apache]
* [Read more on Multi-Processing Modules][apache-MPM]
* [Read more on mod_fastcgi][mod_fastcgi]
* [Read more on mod_fcgid][mod_fcgid]
* [Read more on mod_proxy_fcgi][mod_proxy_fcgi]
* [Read more on setting up Apache and PHP-FPM with mod_proxy_fcgi][tutorial-mod_proxy_fcgi]


[nginx]: https://nginx.org/
[phpfpm]: https://www.php.net/install.fpm
[secure-nginx-phpfpm]: https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/
[apache-modules]: https://httpd.apache.org/docs/2.4/mod/
[prefork MPM]: https://httpd.apache.org/docs/2.4/mod/prefork.html
[worker MPM]: https://httpd.apache.org/docs/2.4/mod/worker.html
[event MPM]: https://httpd.apache.org/docs/2.4/mod/event.html
[apache]: https://httpd.apache.org/
[apache-MPM]: https://httpd.apache.org/docs/2.4/mod/mpm_common.html
[mod_fastcgi]: https://blogs.oracle.com/opal/post/php-fpm-fastcgi-process-manager-with-apache-2
[mod_fcgid]: https://httpd.apache.org/mod_fcgid/
[mod_proxy_fcgi]: https://httpd.apache.org/docs/current/mod/mod_proxy_fcgi.html
[tutorial-mod_proxy_fcgi]: https://serversforhackers.com/video/apache-and-php-fpm


================================================
FILE: _posts/12-04-01-Shared-Servers.md
================================================
---
isChild: true
anchor:  shared_servers
---

## Shared Servers {#shared_servers_title}

PHP has shared servers to thank for its popularity. It is hard to find a host without PHP installed, but be sure it's
the latest version. Shared servers allow you and other developers to deploy websites to a single machine. The upside to
this is that it has become a cheap commodity. The downside is that you never know what kind of a ruckus your
neighboring tenants are going to create; loading down the server or opening up security holes are the main concerns. If
your project's budget can afford to avoid shared servers, you should.

Make sure your shared servers are offering the latest versions of PHP.


================================================
FILE: _posts/12-05-01-Building-your-Application.md
================================================
---
isChild: true
anchor:  building_and_deploying_your_application
---

## Building and Deploying your Application {#building_and_deploying_your_application_title}

If you find yourself doing manual database schema changes or running your tests manually before updating your files
(manually), think twice! With every additional manual task needed to deploy a new version of your app, the chances for
potentially fatal mistakes increase. Whether you're dealing with a simple update, a comprehensive build process or even
a continuous integration strategy, [build automation][buildautomation] is your friend.

Among the tasks you might want to automate are:

* Dependency management
* Compilation, minification of your assets
* Running tests
* Creation of documentation
* Packaging
* Deployment


### Deployment Tools

Deployment tools can be described as a collection of scripts that handle common tasks of software deployment. The deployment tool is not a part of your software, it acts on your software from 'outside'.

There are many open source tools available to help you with build automation and deployment, some are written in PHP others aren't. This shouldn't hold you back from using them, if they're better suited for the specific job. Here are a few examples:

[Phing] can control your packaging, deployment or testing process from within a XML build file. Phing (which is based on [Apache Ant]) provides a rich set of tasks usually needed to install or update a web application and can be extended with additional custom tasks, written in PHP. It's a solid and robust tool and has been around for a long time, however the tool could be perceived as a bit old fashioned because of the way it deals with configuration (XML files).

[Capistrano] is a system for *intermediate-to-advanced programmers* to execute commands in a structured, repeatable way on one or more remote machines. It is pre-configured for deploying Ruby on Rails applications, however you can successfully deploy PHP systems with it. Successful use of Capistrano depends on a working knowledge of Ruby and Rake.

[Ansistrano] is a couple of Ansible roles to easily manage the deployment process (deploy and rollback) for scripting applications such as PHP, Python and Ruby. It's an Ansible port for [Capistrano]. It's been used by quite a lot of PHP companies already.

[Deployer] is a deployment tool written in PHP. It's simple and functional. Features include running tasks in parallel, atomic deployment and keeping consistency between servers. Recipes of common tasks for Symfony, Laravel, Zend Framework and Yii are available. Younes Rafie's article [Easy Deployment of PHP Applications with Deployer][phpdeploy_deployer] is a great tutorial for deploying your application with the tool.

[Magallanes] is another tool written in PHP with simple configuration done in YAML files. It has support for multiple servers and environments, atomic deployment, and has some built in tasks that you can leverage for common tools and frameworks.

#### Further reading:

* [Automate your project with Apache Ant][apache_ant_tutorial]
* [Deploying PHP Applications][deploying_php_applications] - paid book on best practices and tools for PHP deployment.

### Server Provisioning

Managing and configuring servers can be a daunting task when faced with many servers. There are tools for dealing with this so you can automate your infrastructure to make sure you have the right servers and that they're configured properly. They often integrate with the larger cloud hosting providers (Amazon Web Services, Heroku, DigitalOcean, etc) for managing instances, which makes scaling an application a lot easier.

[Ansible] is a tool that manages your infrastructure through YAML files. It's simple to get started with and can manage complex and large scale applications. There is an API for managing cloud instances and it can manage them through a dynamic inventory using certain tools.

[Puppet] is a tool that has its own language and file types for managing servers and configurations. It can be used in a master/client setup or it can be used in a "master-less" mode. In the master/client mode the clients will poll the central master(s) for new configuration on set intervals and update themselves if necessary. In the master-less mode you can push changes to your nodes.

[Chef] is a powerful Ruby based system integration framework that you can build your whole server environment or virtual boxes with. It integrates well with Amazon Web Services through their service called OpsWorks.

#### Further reading:

* [An Ansible Tutorial][an_ansible_tutorial]
* [Ansible for DevOps][ansible_for_devops] - paid book on everything Ansible
* [Ansible for AWS][ansible_for_aws] - paid book on integrating Ansible and Amazon Web Services
* [Three part blog series about deploying a LAMP application with Chef, Vagrant, and EC2][chef_vagrant_and_ec2]
* [Chef Cookbook which installs and configures PHP and the PEAR package management system][Chef_cookbook]
* [Chef video tutorial series][Chef_tutorial]

### Continuous Integration

> Continuous Integration is a software development practice where members of a team integrate their work frequently,
> usually each person integrates at least daily — leading to multiple integrations per day. Many teams find that this
> approach leads to significantly reduced integration problems and allows a team to develop cohesive software more
> rapidly.

*-- Martin Fowler*

There are different ways to implement continuous integration for PHP. [Travis CI] has done a great job of
making continuous integration a reality even for small projects. Travis CI is a hosted continuous integration service.
It can be integrated with GitHub and offers support for many languages including PHP.
GitHub has continuous integration workflows with [GitHub Actions][github_actions].

#### Further reading:

* [Continuous Integration with Jenkins][Jenkins]
* [Continuous Integration with PHPCI][PHPCI]
* [Continuous Integration with PHP Censor][PHP Censor]
* [Continuous Integration with Teamcity][Teamcity]

[buildautomation]: https://wikipedia.org/wiki/Build_automation
[Phing]: https://www.phing.info/
[Apache Ant]: https://ant.apache.org/
[Capistrano]: https://capistranorb.com/
[Ansistrano]: https://ansistrano.com
[phpdeploy_deployer]: https://www.sitepoint.com/deploying-php-applications-with-deployer/
[Chef]: https://www.chef.io/
[chef_vagrant_and_ec2]: https://web.archive.org/web/20190307220000/http://www.jasongrimes.org/2012/06/managing-lamp-environments-with-chef-vagrant-and-ec2-1-of-3/
[Chef_cookbook]: https://github.com/sous-chefs/php
[Chef_tutorial]: https://www.youtube.com/playlist?list=PL11cZfNdwNyNYcpntVe6js-prb80LBZuc
[apache_ant_tutorial]: https://code.tutsplus.com/tutorials/automate-your-projects-with-apache-ant--net-18595
[Travis CI]: https://www.travis-ci.com/
[Jenkins]: https://jenkins.io/
[PHPCI]: https://github.com/dancryer/phpci
[PHP Censor]: https://github.com/php-censor/php-censor
[Teamcity]: https://www.jetbrains.com/teamcity/
[Deployer]: https://deployer.org/
[Magallanes]: https://www.magephp.com/
[deploying_php_applications]: https://deployingphpapplications.com/
[Ansible]: https://www.ansible.com/
[Puppet]: https://puppet.com/
[ansible_for_devops]: https://leanpub.com/ansible-for-devops
[ansible_for_aws]: https://leanpub.com/ansible-for-aws
[an_ansible_tutorial]: https://serversforhackers.com/an-ansible-tutorial
[github_actions]: https://docs.github.com/en/actions


================================================
FILE: _posts/13-01-01-Virtualization.md
================================================
---
anchor: virtualization
---

# Virtualization {#virtualization_title}

Running your application on different environments in development and production can lead to strange bugs popping up
when you go live. It's also tricky to keep different development environments up to date with the same version for all
libraries used when working with a team of developers.

If you are developing on Windows and deploying to Linux (or anything non-Windows) or are developing in a team, you
should consider using a virtual machine. This sounds tricky, but besides the widely known virtualization environments
like VMware or VirtualBox, there are additional tools that may help you setting up a virtual environment in a few easy
steps.


================================================
FILE: _posts/13-02-01-Vagrant.md
================================================
---
isChild: true
anchor:  vagrant
---

## Vagrant {#vagrant_title}

[Vagrant] helps you build your virtual boxes on top of the known virtual environments and will configure these
environments based on a single configuration file. These boxes can be set up manually, or you can use "provisioning"
software such as [Puppet] or [Chef] to do this for you. Provisioning the base box is a great way to ensure that
multiple boxes are set up in an identical fashion and removes the need for you to maintain complicated "set up"
command lists. You can also "destroy" your base box and recreate it without many manual steps, making it easy to create
a "fresh" installation.

Vagrant creates folders for sharing your code between your host and your virtual machine, which means that you can
create and edit your files on your host machine and then run the code inside your virtual machine.


[Vagrant]: https://www.vagrantup.com/
[Puppet]: https://puppet.com/
[Chef]: https://www.chef.io/


================================================
FILE: _posts/13-03-01-Docker.md
================================================
---
isChild: true
anchor:  docker
---

## Docker {#docker_title}

[Docker] - a lightweight alternative to a full virtual machine - is so called because it's all about "containers".  A container is a building block which, in the simplest case, does one specific job, e.g. running a web server.  An "image" is the package you use to build the container - Docker has a repository full of them.

A typical LAMP application might have three containers: a web server, a PHP-FPM process and MySQL. As with shared folders in Vagrant, you can leave your application files where they are and tell Docker where to find them.

You can generate containers from the command line (see example below) or, for ease of maintenance, build a `docker-compose.yml` file for your project specifying which to create and how they communicate with one another.

Docker may help if you're developing multiple websites and want the separation that comes from installing each on its own virtual machine, but don't have the necessary disk space or the time to keep everything up to date.  It's efficient: the installation and downloads are quicker, you only need to store one copy of each image however often it's used, containers need less RAM and share the same OS kernel, so you can have more servers running simultaneously, and it takes a matter of seconds to stop and start them, no need to wait for a full server boot.

### Example: Running your PHP Applications in Docker

After [installing docker][docker-install] on your machine, you can start a web server with one command.
The following will download a fully functional Apache installation with the latest PHP version, map `/path/to/your/php/files` to the document root, which you can view at `http://localhost:8080`:

{% highlight console %}
docker run -d --name my-php-webserver -p 8080:80 -v /path/to/your/php/files:/var/www/html/ php:apache
{% endhighlight %}

This will initialize and launch your container. `-d` makes it run in the background. To stop and start it, simply run `docker stop my-php-webserver` and `docker start my-php-webserver` (the other parameters are not needed again).

### Learn more about Docker

The command above shows a quick way to run a basic server.  There's much more you can do (and thousands of pre-built images in the [Docker Hub][docker-hub]). Take time to learn the terminology and read the [Docker User Guide][docker-doc] to get the most from it, and don't run random code you've downloaded without checking it's safe – unofficial images may not have the latest security patches. If in doubt, stick to the [official repositiories][docker-hub-official].

The [PHPDocker.io] site will auto-generate all the files you need for a fully-featured LAMP/LEMP stack, including your choice of PHP version and extensions.

* [Docker Website][Docker]
* [Docker Installation][docker-install]
* [Docker User Guide][docker-doc]
* [Docker Hub][docker-hub]
* [Docker Hub - official images][docker-hub-official]

[Docker]: https://www.docker.com/
[docker-hub]: https://hub.docker.com/
[docker-hub-official]: https://hub.docker.com/explore/
[docker-install]: https://docs.docker.com/get-docker/
[docker-doc]: https://docs.docker.com/
[PHPDocker.io]: https://phpdocker.io/


================================================
FILE: _posts/14-01-01-Caching.md
================================================
---
anchor: caching
---

# Caching {#caching_title}

PHP is pretty quick by itself, but bottlenecks can arise when you make remote connections, load files, etc. 
Thankfully, there are various tools available to speed up certain parts of your application, or reduce the number of times these various time-consuming tasks need to run.


================================================
FILE: _posts/14-02-01-Opcode-Cache.md
================================================
---
isChild: true
anchor:  opcode_cache
---

## Opcode Cache {#opcode_cache_title}

When a PHP file is executed, it must first be compiled into [opcodes](https://php-legacy-docs.zend.com/manual/php4/en/internals2.opcodes) (machine language instructions for the CPU). If the source code is unchanged, the opcodes will be the same, 
Download .txt
gitextract_5ktl7y4b/

├── .gitignore
├── .ruby-version
├── CNAME
├── CONTRIBUTING.md
├── Gemfile
├── Gruntfile.js
├── LICENSE
├── README.md
├── _config.yml
├── _includes/
│   └── welcome.md
├── _layouts/
│   ├── default.html
│   └── page.html
├── _posts/
│   ├── 01-01-01-Getting-Started.md
│   ├── 01-02-01-Use-the-Current-Stable-Version.md
│   ├── 01-03-01-Built-in-Web-Server.md
│   ├── 01-04-01-Mac-Setup.md
│   ├── 01-05-01-Windows-Setup.md
│   ├── 01-06-01-Linux-Setup.md
│   ├── 01-07-01-Common-Directory-Structure.md
│   ├── 02-01-01-Code-Style-Guide.md
│   ├── 03-01-01-Language-Highlights.md
│   ├── 03-02-01-Programming-Paradigms.md
│   ├── 03-03-01-Namespaces.md
│   ├── 03-04-01-Standard-PHP-Library.md
│   ├── 03-05-01-Command-Line-Interface.md
│   ├── 03-06-01-XDebug.md
│   ├── 04-01-01-Dependency-Management.md
│   ├── 04-02-01-Composer-and-Packagist.md
│   ├── 04-03-01-PEAR.md
│   ├── 05-01-01-Coding-Practices.md
│   ├── 05-02-01-The-Basics.md
│   ├── 05-03-01-Date-and-Time.md
│   ├── 05-04-01-Design-Patterns.md
│   ├── 05-05-01-PHP-and-UTF8.md
│   ├── 05-06-01-Internationalization-and-Localization.md
│   ├── 06-01-01-Dependency-Injection.md
│   ├── 06-02-01-Basic-Concept.md
│   ├── 06-03-01-Complex-Problem.md
│   ├── 06-04-01-Containers.md
│   ├── 06-05-01-Further-Reading.md
│   ├── 07-01-01-Databases.md
│   ├── 07-02-01-Databases_MySQL.md
│   ├── 07-03-01-Databases_PDO.md
│   ├── 07-04-01-Interacting-via-Code.md
│   ├── 07-05-01-Abstraction-Layers.md
│   ├── 08-01-01-Templating.md
│   ├── 08-02-01-Benefits.md
│   ├── 08-03-01-Plain-PHP-Templates.md
│   ├── 08-04-01-Compiled-Templates.md
│   ├── 08-05-01-Further-Reading.md
│   ├── 09-01-01-Errors-and-Exceptions.md
│   ├── 09-02-01-Errors.md
│   ├── 09-03-01-Exceptions.md
│   ├── 10-01-01-Security.md
│   ├── 10-02-01-Web-Application-Security.md
│   ├── 10-03-01-Password-Hashing.md
│   ├── 10-04-01-Data-Filtering.md
│   ├── 10-05-01-Configuration-Files.md
│   ├── 10-06-01-Register-Globals.md
│   ├── 10-07-01-Error-Reporting.md
│   ├── 11-01-01-Testing.md
│   ├── 11-02-01-Test-Driven-Development.md
│   ├── 11-03-01-Behavior-Driven-Development.md
│   ├── 11-04-01-Complementary-Testing-Tools.md
│   ├── 12-01-01-Servers-and-Deployment.md
│   ├── 12-02-01-Platform-as-a-Service.md
│   ├── 12-03-01-Virtual-or-Dedicated-Servers.md
│   ├── 12-04-01-Shared-Servers.md
│   ├── 12-05-01-Building-your-Application.md
│   ├── 13-01-01-Virtualization.md
│   ├── 13-02-01-Vagrant.md
│   ├── 13-03-01-Docker.md
│   ├── 14-01-01-Caching.md
│   ├── 14-02-01-Opcode-Cache.md
│   ├── 14-03-01-Object-Caching.md
│   ├── 15-01-01-Documenting.md
│   ├── 15-02-01-PHPDoc.md
│   ├── 16-01-01-Resources.md
│   ├── 16-02-01-From-the-Source.md
│   ├── 16-03-01-People-to-Follow.md
│   ├── 16-05-01-PHP-PaaS-Providers.md
│   ├── 16-06-01-Frameworks.md
│   ├── 16-07-01-Components.md
│   ├── 16-08-01-Sites.md
│   ├── 16-09-01-Videos.md
│   ├── 16-10-01-Books.md
│   ├── 17-01-01-Community.md
│   ├── 17-02-01-User-Groups.md
│   ├── 17-03-01-Conferences.md
│   └── 17-04-01-Elephpants.md
├── banners.md
├── css/
│   └── all.css
├── index.html
├── less/
│   └── all.less
├── package.json
├── pages/
│   ├── Design-Patterns.md
│   ├── Functional-Programming.md
│   ├── The-Basics.md
│   └── example.md
├── scripts/
│   ├── fastclick.js
│   └── setup.js
└── styles/
    ├── all.css
    ├── all.less
    ├── base/
    │   ├── all.less
    │   ├── bars-buttons.less
    │   ├── buttons.less
    │   ├── grid.less
    │   ├── idioms.less
    │   ├── prefixer.less
    │   ├── reset.less
    │   ├── spacing.less
    │   ├── typography.less
    │   └── variables.less
    ├── print.css
    ├── site/
    │   ├── site-content.less
    │   ├── site-footer.less
    │   ├── site-header.less
    │   ├── site-navigation.less
    │   └── variables.less
    └── syntax.css
Download .txt
SYMBOL INDEX (3 symbols across 1 files)

FILE: scripts/fastclick.js
  function e (line 4) | function e(o){if(n[o])return n[o].exports;var i=n[o]={exports:{},id:o,lo...
  function e (line 4) | function e(t,n){function o(t,e){return function(){return t.apply(e,argum...
  function n (line 4) | function n(t){t in o||(o[t]=!0,document.dispatchEvent(new CustomEvent("o...
Condensed preview — 120 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (440K chars).
[
  {
    "path": ".gitignore",
    "chars": 47,
    "preview": "/_site/\n*.DS_Store\nnode_modules\nvendor\n.bundle\n"
  },
  {
    "path": ".ruby-version",
    "chars": 6,
    "preview": "2.7.8\n"
  },
  {
    "path": "CNAME",
    "chars": 18,
    "preview": "phptherightway.com"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 4490,
    "preview": "# Contributing to PHP The Right Way\n\nEnjoy [PHP The Right Way](https://phptherightway.com) and want to get\ninvolved? Gre"
  },
  {
    "path": "Gemfile",
    "chars": 85,
    "preview": "source 'https://rubygems.org'\ngem 'github-pages', group: :jekyll_plugins\ngem 'rouge'\n"
  },
  {
    "path": "Gruntfile.js",
    "chars": 1275,
    "preview": "module.exports = function(grunt) {\n    // Project configuration\n    grunt.initConfig({\n        pkg: grunt.file.readJSON("
  },
  {
    "path": "LICENSE",
    "chars": 85,
    "preview": "Copyright (c) 2025 Josh Lockhart\n\nhttps://creativecommons.org/licenses/by-nc-sa/3.0/\n"
  },
  {
    "path": "README.md",
    "chars": 3838,
    "preview": "# PHP: The Right Way\n\n## Overview\n\nThis is the GitHub Pages repository for the _PHP: The Right Way_ project.\n\n* This web"
  },
  {
    "path": "_config.yml",
    "chars": 1162,
    "preview": "baseurl: /\nhighlighter: rouge\nmarkdown: kramdown\npermalink: date\nmaruku:\n    use_tex:    false\n    use_divs:   false\n   "
  },
  {
    "path": "_includes/welcome.md",
    "chars": 2488,
    "preview": "# Welcome\n\nThere's a lot of outdated information on the Web that leads new PHP users astray,\npropagating bad practices a"
  },
  {
    "path": "_layouts/default.html",
    "chars": 13447,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"utf-8\"/>\n\n        {% seo %}\n\n        <meta name=\"robo"
  },
  {
    "path": "_layouts/page.html",
    "chars": 12070,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n    <head>\n        <meta charset=\"utf-8\"/>\n\n        {% seo %}\n\n        <meta name=\"robo"
  },
  {
    "path": "_posts/01-01-01-Getting-Started.md",
    "chars": 77,
    "preview": "---\nanchor: getting_started\n---\n\n# Getting Started {#getting_started_title}\n\n"
  },
  {
    "path": "_posts/01-02-01-Use-the-Current-Stable-Version.md",
    "chars": 1580,
    "preview": "---\ntitle:   Use the Current Stable Version (8.5)\nisChild: true\nanchor:  use_the_current_stable_version\n---\n\n## Use the "
  },
  {
    "path": "_posts/01-03-01-Built-in-Web-Server.md",
    "chars": 540,
    "preview": "---\ntitle:   Built-in Web Server\nisChild: true\nanchor:  builtin_web_server\n---\n\n## Built-in web server {#builtin_web_ser"
  },
  {
    "path": "_posts/01-04-01-Mac-Setup.md",
    "chars": 3640,
    "preview": "---\nisChild: true\nanchor:  mac_setup\n---\n\n## macOS Setup {#mac_setup_title}\n\nmacOS 12 (Monterey) and later does not come"
  },
  {
    "path": "_posts/01-05-01-Windows-Setup.md",
    "chars": 2164,
    "preview": "---\nisChild: true\nanchor:  windows_setup\n---\n\n## Windows Setup {#windows_setup_title}\n\nYou can download the binaries fro"
  },
  {
    "path": "_posts/01-06-01-Linux-Setup.md",
    "chars": 3002,
    "preview": "---\nisChild: true\nanchor:  linux_setup\n---\n\n## Linux Setup {#linux_setup_title}\n\nMost GNU/Linux distributions come with "
  },
  {
    "path": "_posts/01-07-01-Common-Directory-Structure.md",
    "chars": 1600,
    "preview": "---\ntitle:   Common Directory Structure\nisChild: true\nanchor:  common_directory_structure\n---\n\n## Common Directory struc"
  },
  {
    "path": "_posts/02-01-01-Code-Style-Guide.md",
    "chars": 3732,
    "preview": "---\nanchor: code_style_guide\n---\n\n# Code Style Guide {#code_style_guide_title}\n\nThe PHP community is large and diverse, "
  },
  {
    "path": "_posts/03-01-01-Language-Highlights.md",
    "chars": 88,
    "preview": "---\nanchor: language_highlights\n---\n\n# Language Highlights {#language_highlights_title}\n"
  },
  {
    "path": "_posts/03-02-01-Programming-Paradigms.md",
    "chars": 2935,
    "preview": "---\nisChild: true\nanchor:  programming_paradigms\n---\n\n## Programming Paradigms {#programming_paradigms_title}\n\nPHP is a "
  },
  {
    "path": "_posts/03-03-01-Namespaces.md",
    "chars": 1520,
    "preview": "---\nisChild: true\nanchor:  namespaces\n---\n\n## Namespaces {#namespaces_title}\n\nAs mentioned above, the PHP community has "
  },
  {
    "path": "_posts/03-04-01-Standard-PHP-Library.md",
    "chars": 681,
    "preview": "---\ntitle:   Standard PHP Library\nisChild: true\nanchor:  standard_php_library\n---\n\n## Standard PHP Library {#standard_ph"
  },
  {
    "path": "_posts/03-05-01-Command-Line-Interface.md",
    "chars": 2283,
    "preview": "---\nisChild: true\nanchor:  command_line_interface\n---\n\n## Command Line Interface {#command_line_interface_title}\n\nPHP wa"
  },
  {
    "path": "_posts/03-06-01-XDebug.md",
    "chars": 2033,
    "preview": "---\ntitle:   Xdebug\nisChild: true\nanchor:  xdebug\n---\n\n## Xdebug {#xdebug_title}\n\nOne of the most useful tools in softwa"
  },
  {
    "path": "_posts/04-01-01-Dependency-Management.md",
    "chars": 807,
    "preview": "---\nanchor: dependency_management\n---\n\n# Dependency Management {#dependency_management_title}\n\nThere are a ton of PHP li"
  },
  {
    "path": "_posts/04-02-01-Composer-and-Packagist.md",
    "chars": 5075,
    "preview": "---\ntitle:   Composer and Packagist\nisChild: true\nanchor:  composer_and_packagist\n---\n\n## Composer and Packagist {#compo"
  },
  {
    "path": "_posts/04-03-01-PEAR.md",
    "chars": 3590,
    "preview": "---\ntitle:   PEAR\nisChild: true\nanchor:  pear\n---\n\n## PEAR {#pear_title}\n\nA veteran package manager that some PHP develo"
  },
  {
    "path": "_posts/05-01-01-Coding-Practices.md",
    "chars": 79,
    "preview": "---\nanchor: coding_practices\n---\n\n# Coding Practices {#coding_practices_title}\n"
  },
  {
    "path": "_posts/05-02-01-The-Basics.md",
    "chars": 527,
    "preview": "---\nisChild: true\nanchor:  the_basics\n---\n\n## The Basics {#the_basics_title}\n\nPHP is a vast language that allows coders "
  },
  {
    "path": "_posts/05-03-01-Date-and-Time.md",
    "chars": 2966,
    "preview": "---\ntitle:   Date and Time\nisChild: true\nanchor:  date_and_time\n---\n\n## Date and Time {#date_and_time_title}\n\nPHP has a "
  },
  {
    "path": "_posts/05-04-01-Design-Patterns.md",
    "chars": 1209,
    "preview": "---\nisChild: true\nanchor:  design_patterns\n---\n\n## Design Patterns {#design_patterns_title}\n\nWhen you are building your "
  },
  {
    "path": "_posts/05-05-01-PHP-and-UTF8.md",
    "chars": 8321,
    "preview": "---\ntitle:   Working with UTF-8\nisChild: true\nanchor:  php_and_utf8\n---\n\n## Working with UTF-8 {#php_and_utf8_title}\n\n_T"
  },
  {
    "path": "_posts/05-06-01-Internationalization-and-Localization.md",
    "chars": 25705,
    "preview": "---\ntitle:   Internationalization and Localization\nisChild: true\nanchor:  i18n_l10n\n---\n\n## Internationalization (i18n) "
  },
  {
    "path": "_posts/06-01-01-Dependency-Injection.md",
    "chars": 616,
    "preview": "---\ntitle:  Dependency Injection\nanchor: dependency_injection\n---\n\n# Dependency Injection {#dependency_injection_title}\n"
  },
  {
    "path": "_posts/06-02-01-Basic-Concept.md",
    "chars": 1467,
    "preview": "---\nisChild: true\nanchor:  basic_concept\n---\n\n## Basic Concept {#basic_concept_title}\n\nWe can demonstrate the concept wi"
  },
  {
    "path": "_posts/06-03-01-Complex-Problem.md",
    "chars": 6172,
    "preview": "---\nisChild: true\nanchor:  complex_problem\n---\n\n## Complex Problem {#complex_problem_title}\n\nIf you have ever read about"
  },
  {
    "path": "_posts/06-04-01-Containers.md",
    "chars": 900,
    "preview": "---\nisChild: true\nanchor:  containers\n---\n\n## Containers {#containers_title}\n\nThe first thing you should understand abou"
  },
  {
    "path": "_posts/06-05-01-Further-Reading.md",
    "chars": 532,
    "preview": "---\nisChild: true\nanchor:  further_reading\n---\n\n## Further Reading {#further_reading_title}\n\n* [What is Dependency Injec"
  },
  {
    "path": "_posts/07-01-01-Databases.md",
    "chars": 768,
    "preview": "---\ntitle:  Databases\nanchor: databases\n---\n\n# Databases {#databases_title}\n\nMany times your PHP code will use a databas"
  },
  {
    "path": "_posts/07-02-01-Databases_MySQL.md",
    "chars": 1698,
    "preview": "---\nisChild: true\ntitle:   MySQL Extension\nanchor:  mysql_extension\n---\n\n## MySQL Extension {#mysql_extension_title}\n\nTh"
  },
  {
    "path": "_posts/07-03-01-Databases_PDO.md",
    "chars": 3680,
    "preview": "---\nisChild: true\ntitle:   PDO Extension\nanchor:  pdo_extension\n---\n\n## PDO Extension {#pdo_extension_title}\n\n[PDO] is a"
  },
  {
    "path": "_posts/07-04-01-Interacting-via-Code.md",
    "chars": 2709,
    "preview": "---\nisChild: true\ntitle:   Interacting with Databases\nanchor:  databases_interacting\n---\n\n## Interacting with Databases "
  },
  {
    "path": "_posts/07-05-01-Abstraction-Layers.md",
    "chars": 1279,
    "preview": "---\nisChild: true\ntitle:   Abstraction Layers\nanchor:  databases_abstraction_layers\n---\n\n## Abstraction Layers {#databas"
  },
  {
    "path": "_posts/08-01-01-Templating.md",
    "chars": 513,
    "preview": "---\ntitle:  Templating\nanchor: templating\n---\n\n# Templating {#templating_title}\n\nTemplates provide a convenient way of s"
  },
  {
    "path": "_posts/08-02-01-Benefits.md",
    "chars": 1268,
    "preview": "---\nisChild: true\nanchor:  templating_benefits\n---\n\n## Benefits {#templating_benefits_title}\n\nThe main benefit to using "
  },
  {
    "path": "_posts/08-03-01-Plain-PHP-Templates.md",
    "chars": 1830,
    "preview": "---\ntitle: Plain PHP Templates\nisChild: true\nanchor:  plain_php_templates\n---\n\n## Plain PHP Templates {#plain_php_templa"
  },
  {
    "path": "_posts/08-04-01-Compiled-Templates.md",
    "chars": 1969,
    "preview": "---\nisChild: true\nanchor:  compiled_templates\n---\n\n## Compiled Templates {#compiled_templates_title}\n\nWhile PHP has evol"
  },
  {
    "path": "_posts/08-05-01-Further-Reading.md",
    "chars": 1536,
    "preview": "---\nisChild: true\nanchor:  templating_further_reading\n---\n\n## Further Reading {#templating_further_reading_title}\n\n### A"
  },
  {
    "path": "_posts/09-01-01-Errors-and-Exceptions.md",
    "chars": 125,
    "preview": "---\ntitle:  Errors and Exceptions\nanchor: errors_and_exceptions\n---\n\n# Errors and Exceptions {#errors_and_exceptions_tit"
  },
  {
    "path": "_posts/09-02-01-Errors.md",
    "chars": 7418,
    "preview": "---\nisChild: true\nanchor:  errors\n---\n\n## Errors {#errors_title}\n\nIn many \"exception-heavy\" programming languages, whene"
  },
  {
    "path": "_posts/09-03-01-Exceptions.md",
    "chars": 3015,
    "preview": "---\nisChild: true\nanchor:  exceptions\n---\n\n## Exceptions {#exceptions_title}\n\nExceptions are a standard part of most pop"
  },
  {
    "path": "_posts/10-01-01-Security.md",
    "chars": 278,
    "preview": "---\nanchor: security\n---\n\n# Security {#security_title}\n\nThe best resource I've found on PHP security is [The 2018 Guide "
  },
  {
    "path": "_posts/10-02-01-Web-Application-Security.md",
    "chars": 2075,
    "preview": "---\nisChild: true\nanchor:  web_application_security\n---\n\n## Web Application Security {#web_application_security_title}\n\n"
  },
  {
    "path": "_posts/10-03-01-Password-Hashing.md",
    "chars": 3470,
    "preview": "---\nisChild: true\nanchor:  password_hashing\n---\n\n## Password Hashing {#password_hashing_title}\n\nEventually everyone buil"
  },
  {
    "path": "_posts/10-04-01-Data-Filtering.md",
    "chars": 4026,
    "preview": "---\nisChild: true\nanchor:  data_filtering\n---\n\n## Data Filtering {#data_filtering_title}\n\nNever ever (ever) trust foreig"
  },
  {
    "path": "_posts/10-05-01-Configuration-Files.md",
    "chars": 866,
    "preview": "---\nisChild: true\nanchor:  configuration_files\n---\n\n## Configuration Files {#configuration_files_title}\n\nWhen creating c"
  },
  {
    "path": "_posts/10-06-01-Register-Globals.md",
    "chars": 802,
    "preview": "---\nisChild: true\nanchor:  register_globals\n---\n\n## Register Globals {#register_globals_title}\n\n**NOTE:** As of PHP 5.4."
  },
  {
    "path": "_posts/10-07-01-Error-Reporting.md",
    "chars": 2141,
    "preview": "---\nisChild: true\nanchor:  error_reporting\n---\n\n## Error Reporting {#error_reporting_title}\n\nError logging can be useful"
  },
  {
    "path": "_posts/11-01-01-Testing.md",
    "chars": 615,
    "preview": "---\nanchor: testing\n---\n\n# Testing {#testing_title}\n\nWriting automated tests for your PHP code is considered a best prac"
  },
  {
    "path": "_posts/11-02-01-Test-Driven-Development.md",
    "chars": 4038,
    "preview": "---\nisChild: true\nanchor:  test_driven_development\n---\n\n## Test Driven Development {#test_driven_development_title}\n\nFro"
  },
  {
    "path": "_posts/11-03-01-Behavior-Driven-Development.md",
    "chars": 1456,
    "preview": "---\nisChild: true\nanchor:  behavior_driven_development\n---\n\n## Behavior Driven Development {#behavior_driven_development"
  },
  {
    "path": "_posts/11-04-01-Complementary-Testing-Tools.md",
    "chars": 1496,
    "preview": "---\nisChild: true\nanchor:  complementary_testing_tools\n---\n\n## Complementary Testing Tools {#complementary_testing_tools"
  },
  {
    "path": "_posts/12-01-01-Servers-and-Deployment.md",
    "chars": 217,
    "preview": "---\ntitle:  Servers and Deployment\nanchor: servers_and_deployment\n---\n\n# Servers and Deployment {#servers_and_deployment"
  },
  {
    "path": "_posts/12-02-01-Platform-as-a-Service.md",
    "chars": 578,
    "preview": "---\ntitle:   Platform as a Service (PaaS)\nisChild: true\nanchor:  platform_as_a_service\n---\n\n## Platform as a Service (Pa"
  },
  {
    "path": "_posts/12-03-01-Virtual-or-Dedicated-Servers.md",
    "chars": 3249,
    "preview": "---\ntitle:   Virtual or Dedicated Servers\nisChild: true\nanchor:  virtual_or_dedicated_servers\n---\n\n## Virtual or Dedicat"
  },
  {
    "path": "_posts/12-04-01-Shared-Servers.md",
    "chars": 699,
    "preview": "---\nisChild: true\nanchor:  shared_servers\n---\n\n## Shared Servers {#shared_servers_title}\n\nPHP has shared servers to than"
  },
  {
    "path": "_posts/12-05-01-Building-your-Application.md",
    "chars": 7506,
    "preview": "---\nisChild: true\nanchor:  building_and_deploying_your_application\n---\n\n## Building and Deploying your Application {#bui"
  },
  {
    "path": "_posts/13-01-01-Virtualization.md",
    "chars": 725,
    "preview": "---\nanchor: virtualization\n---\n\n# Virtualization {#virtualization_title}\n\nRunning your application on different environm"
  },
  {
    "path": "_posts/13-02-01-Vagrant.md",
    "chars": 979,
    "preview": "---\nisChild: true\nanchor:  vagrant\n---\n\n## Vagrant {#vagrant_title}\n\n[Vagrant] helps you build your virtual boxes on top"
  },
  {
    "path": "_posts/13-03-01-Docker.md",
    "chars": 3225,
    "preview": "---\nisChild: true\nanchor:  docker\n---\n\n## Docker {#docker_title}\n\n[Docker] - a lightweight alternative to a full virtual"
  },
  {
    "path": "_posts/14-01-01-Caching.md",
    "chars": 333,
    "preview": "---\nanchor: caching\n---\n\n# Caching {#caching_title}\n\nPHP is pretty quick by itself, but bottlenecks can arise when you m"
  },
  {
    "path": "_posts/14-02-01-Opcode-Cache.md",
    "chars": 1680,
    "preview": "---\nisChild: true\nanchor:  opcode_cache\n---\n\n## Opcode Cache {#opcode_cache_title}\n\nWhen a PHP file is executed, it must"
  },
  {
    "path": "_posts/14-03-01-Object-Caching.md",
    "chars": 2935,
    "preview": "---\nisChild: true\nanchor:  object_caching\n---\n\n## Object Caching {#object_caching_title}\n\nThere are times when it can be"
  },
  {
    "path": "_posts/15-01-01-Documenting.md",
    "chars": 104,
    "preview": "---\nanchor: documenting\ntitle:  Documenting your Code\n---\n\n# Documenting your Code {#documenting_title}\n"
  },
  {
    "path": "_posts/15-02-01-PHPDoc.md",
    "chars": 2897,
    "preview": "---\nisChild: true\ntitle:   PHPDoc\nanchor:  phpdoc\n---\n\n## PHPDoc {#phpdoc_title}\n\nPHPDoc is an informal standard for com"
  },
  {
    "path": "_posts/16-01-01-Resources.md",
    "chars": 58,
    "preview": "---\nanchor: resources\n---\n\n# Resources {#resources_title}\n"
  },
  {
    "path": "_posts/16-02-01-From-the-Source.md",
    "chars": 208,
    "preview": "---\ntitle:   From the Source\nisChild: true\nanchor:  from_the_source\n---\n\n## From the Source {#from_the_source_title}\n\n* "
  },
  {
    "path": "_posts/16-03-01-People-to-Follow.md",
    "chars": 443,
    "preview": "---\ntitle:   People to Follow\nisChild: true\nanchor:  people_to_follow\n---\n\n## People to Follow {#people_to_follow_title}"
  },
  {
    "path": "_posts/16-05-01-PHP-PaaS-Providers.md",
    "chars": 1077,
    "preview": "---\ntitle: PHP PaaS Providers\nisChild: true\nanchor:  php_paas_providers\n---\n\n## PHP PaaS Providers {#php_paas_providers_"
  },
  {
    "path": "_posts/16-06-01-Frameworks.md",
    "chars": 1245,
    "preview": "---\nisChild: true\nanchor:  frameworks\n---\n\n## Frameworks {#frameworks_title}\n\nRather than re-invent the wheel, many PHP "
  },
  {
    "path": "_posts/16-07-01-Components.md",
    "chars": 2234,
    "preview": "---\nisChild: true\nanchor:  components\n---\n\n## Components {#components_title}\n\nAs mentioned above \"Components\" are anothe"
  },
  {
    "path": "_posts/16-08-01-Sites.md",
    "chars": 1428,
    "preview": "---\nisChild: true\nanchor:  other_resources\ntitle:   Other Useful Resources\n---\n\n## Other Useful Resources {#other_resour"
  },
  {
    "path": "_posts/16-09-01-Videos.md",
    "chars": 944,
    "preview": "---\nisChild: true\nanchor:  videos\ntitle:   Video Tutorials\n---\n\n## Video Tutorials {#videos}\n\n### YouTube Channels\n\n* [L"
  },
  {
    "path": "_posts/16-10-01-Books.md",
    "chars": 2650,
    "preview": "---\nisChild: true\nanchor:  books\n---\n\n## Books {#books_title}\n\nThere are many PHP books; sadly some are now quite old an"
  },
  {
    "path": "_posts/17-01-01-Community.md",
    "chars": 928,
    "preview": "---\nanchor: community\n---\n\n# Community {#community_title}\n\nThe PHP community is as diverse as it is large, and its membe"
  },
  {
    "path": "_posts/17-02-01-User-Groups.md",
    "chars": 1287,
    "preview": "---\nisChild: true\nanchor:  user_groups\n---\n\n## PHP User Groups {#user_groups_title}\n\nIf you live in a larger city, odds "
  },
  {
    "path": "_posts/17-03-01-Conferences.md",
    "chars": 429,
    "preview": "---\nisChild: true\nanchor:  conferences\n---\n\n## PHP Conferences {#conferences_title}\n\nThe PHP community also hosts larger"
  },
  {
    "path": "_posts/17-04-01-Elephpants.md",
    "chars": 742,
    "preview": "---\nisChild: true\nanchor:  elephpants\n---\n\n## ElePHPants {#elephpants_title}\n\n[ElePHPant][elephpant] is that beautiful m"
  },
  {
    "path": "banners.md",
    "chars": 2720,
    "preview": "---\nlayout: page\ntitle: Website Banners\ndescription: \"Spread the word! Use these banner to let new PHP programmers know "
  },
  {
    "path": "css/all.css",
    "chars": 25115,
    "preview": "*{box-sizing:border-box}body{font-size:24px;line-height:32px;text-rendering:optimizeLegibility}h1,h2,h3,h4{font-family:g"
  },
  {
    "path": "index.html",
    "chars": 520,
    "preview": "---\nlayout: default\nsitemap: true\n---\n\n{% capture welcome_content %}{% include welcome.md %}{% endcapture %}\n<section cl"
  },
  {
    "path": "less/all.less",
    "chars": 13110,
    "preview": "/******************************************************************************\n * Variables\n **************************"
  },
  {
    "path": "package.json",
    "chars": 240,
    "preview": "{\n  \"name\": \"php-the-right-way\",\n  \"version\": \"2.0.0\",\n  \"devDependencies\": {\n    \"grunt\": \"~0.4.5\",\n    \"grunt-contrib-"
  },
  {
    "path": "pages/Design-Patterns.md",
    "chars": 8858,
    "preview": "---\nlayout: page\ntitle:  Design Patterns\nsitemap: true\n---\n\n# Design Patterns\n\nThere are numerous ways to structure the "
  },
  {
    "path": "pages/Functional-Programming.md",
    "chars": 3592,
    "preview": "---\nlayout: page\ntitle:  Functional Programming in PHP\nsitemap: true\n---\n\n# Functional Programming in PHP\n\nPHP supports "
  },
  {
    "path": "pages/The-Basics.md",
    "chars": 12681,
    "preview": "---\nlayout: page\ntitle:  The Basics\nsitemap: true\n---\n\n# The Basics\n\n## Comparison operators\n\nComparison operators are a"
  },
  {
    "path": "pages/example.md",
    "chars": 1411,
    "preview": "---\nlayout: page\ntitle: Example Stand-Alone Page\n---\n\n# Page Title\n\nLorem ipsum dolor sit amet, consectetur adipisicing "
  },
  {
    "path": "scripts/fastclick.js",
    "chars": 8793,
    "preview": "/** Shrinkwrap URL:\n *      /v2/bundles/js?modules=fastclick%401.0.6%2Co-autoinit%401.0.1&shrinkwrap=\n */\n!function(t){f"
  },
  {
    "path": "scripts/setup.js",
    "chars": 482,
    "preview": "(function ($) {\n    // Attach FastClick\n    var attachFastClick = Origami.fastclick;\n    attachFastClick(document.body);"
  },
  {
    "path": "styles/all.css",
    "chars": 84917,
    "preview": "/* ==========================================================================\n   NMC Bootstrap\n\n   This LESS file import"
  },
  {
    "path": "styles/all.less",
    "chars": 1570,
    "preview": "/* ==========================================================================\n   NMC Bootstrap\n\n   This LESS file import"
  },
  {
    "path": "styles/base/all.less",
    "chars": 154,
    "preview": "@import \"reset\";\n@import \"prefixer\";\n@import \"spacing\";\n@import \"typography\";\n@import \"idioms\";\n@import \"grid\";\n@import "
  },
  {
    "path": "styles/base/bars-buttons.less",
    "chars": 5295,
    "preview": ".button() {\n    .border-box;\n    cursor: pointer;\n    display: inline-block;\n    .phh;\n    text-align: center;\n    font-"
  },
  {
    "path": "styles/base/buttons.less",
    "chars": 2799,
    "preview": "/* ==========================================================================\n   Settings\n   ==========================="
  },
  {
    "path": "styles/base/grid.less",
    "chars": 5491,
    "preview": "/**\n * Hybrid Grid Sytem\n *\n * Blend of the Semantic Grid System and Zurb Foundation with a little Twitter Bootstrap\n */"
  },
  {
    "path": "styles/base/idioms.less",
    "chars": 1827,
    "preview": "/**\n * New Media Campaigns Idioms\n *\n * These are common patterns we use in all of our\n * projects. They are consolidate"
  },
  {
    "path": "styles/base/prefixer.less",
    "chars": 11417,
    "preview": "/*---------------------------------------------------\n    LESS Prefixer\n  ----------------------------------------------"
  },
  {
    "path": "styles/base/reset.less",
    "chars": 1781,
    "preview": "/**\n * html5doctor.com Reset Stylesheet\n * v1.6.1\n * Last Updated: 2010-09-17\n * Author: Richard Clark - http://richclar"
  },
  {
    "path": "styles/base/spacing.less",
    "chars": 2556,
    "preview": "/**\n * Spacing\n *\n * This LESS file defines margins and paddings for block-level\n * elements. Helper classes are include"
  },
  {
    "path": "styles/base/typography.less",
    "chars": 6732,
    "preview": "/**\n * Name Here\n *\n * @version     1.0\n * @package     Name Here\n * @author      New Media Campaigns\n * @copyright   20"
  },
  {
    "path": "styles/base/variables.less",
    "chars": 1665,
    "preview": "/* ==========================================================================\n   Spacing\n   ============================"
  },
  {
    "path": "styles/print.css",
    "chars": 178,
    "preview": "body, .site-title, h1, h2, h3{\n\tfont-family: 'Georgia' !important;\n}\n\n\nnav.site-navigation, a.fork-me, a.top{\n\tdisplay:n"
  },
  {
    "path": "styles/site/site-content.less",
    "chars": 322,
    "preview": ".site-content{\n    padding: 20px 40px 40px 320px;\n\n    h1{\n        clear: both;\n    }\n}\n.interior-site-content{\n    .pad"
  },
  {
    "path": "styles/site/site-footer.less",
    "chars": 258,
    "preview": ".site-footer{\n    clear: both;\n    .ptd;\n    font-size: 13px;\n    text-align: center;\n}\n.site-footer img{\n    margin-lef"
  },
  {
    "path": "styles/site/site-header.less",
    "chars": 707,
    "preview": ".site-header{\n    position: relative;\n    z-index: 1;\n    text-align: center;\n}\n.site-title{\n    .mbn;\n    font-family: "
  },
  {
    "path": "styles/site/site-navigation.less",
    "chars": 721,
    "preview": ".site-navigation{\n    background: #EEE;\n    .inner-shadow(fade(#000, 7%) 0 0 40px);\n    .pas;\n    position: fixed;\n    t"
  },
  {
    "path": "styles/site/variables.less",
    "chars": 1407,
    "preview": "/* ==========================================================================\n   Spacing\n   ============================"
  },
  {
    "path": "styles/syntax.css",
    "chars": 3770,
    "preview": ".highlight  { background: #ffffff; margin: 0 4px; font-size: 0.8em; }\n.highlight .c { color: #999988; font-style: italic"
  }
]

About this extraction

This page contains the full source code of the codeguy/php-the-right-way GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 120 files (411.9 KB), approximately 125.7k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!