PHP Deployment & Hosting
In this page:
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
$env = getenv('APP_ENV') ?: 'local';
echo "Running in $env mode";
?>
Login to try C/C++/Java/PHP code in the editor
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
file_put_contents('.env', "DB_PASSWORD=secret123\n");
echo "Secrets belong in .env, excluded from version control, not hardcoded in PHP";
?>
Login to try C/C++/Java/PHP code in the editor
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
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";
?>
Login to try C/C++/Java/PHP code in the editor
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
function deploy() {
echo "Clearing cache...\n";
echo "Running migrations...\n";
echo "Deploy complete";
}
deploy();
?>
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: