← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 5 of 10

PHP Deployment & Hosting

Introduction to Deployment

Deployment is the process of moving code from your local machine to a live server where real users can reach it; checking environment variables lets the same codebase behave differently in local versus production settings.

Example: Introduction to Deployment

php
<?php
$env = getenv('APP_ENV') ?: 'local';
echo "Running in $env mode";
?>

Environment Configurations (.env)

Secrets like database passwords and API keys belong in a .env file that's excluded from version control, never hardcoded directly into PHP files where they could leak if the source is ever exposed.

Example: Environment Configurations (.env)

php
<?php
file_put_contents('.env', "DB_PASSWORD=secret123\n");
echo "Secrets belong in .env, excluded from version control, not hardcoded in PHP";
?>

Folder Permissions

Upload and cache directories need write permissions so PHP can save files there, while the rest of your codebase should stay read-only on production to limit the damage a compromised script could do.

Example: Folder Permissions

php
<?php
mkdir('uploads', 0755);
chmod('uploads', 0775); // writable for uploads, unlike the rest of the codebase
echo "Upload directory is writable; source code stays read-only";
?>

Automated Deploy Scripts

An automated deploy script can clear stale caches and run pending database migrations as part of every release, removing the risk of a human forgetting a manual step during deployment.

Example: Automated Deploy Scripts

php
<?php
function deploy() {
    echo "Clearing cache...\n";
    echo "Running migrations...\n";
    echo "Deploy complete";
}
deploy();
?>

Production Error Handling

Showing PHP's default error output to visitors on a live site leaks file paths and internal logic to anyone who triggers an error; production servers should log details privately while showing users a generic message.

Example: Production Error Handling

php
<?php
ini_set('display_errors', '0');
error_reporting(E_ALL);
ini_set('log_errors', '1');
echo "Errors are logged privately, not shown to visitors";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.