العربية ← Back to Module README

Module 15: Deployment

Lesson 1: Understanding Hosting Options

Instructor notes

Most beginners confuse hosting types. Emphasize that shared hosting is the easiest starting point, but free hosts like InfinityFree have limitations (ads, downtime, no root access). Use analogies: shared hosting is like renting a room in a shared house; VPS is like owning an apartment building.

Presentation outline

  1. What is web hosting?
  2. Types of hosting: shared, VPS, dedicated, cloud, free
  3. Comparing cost, control, and difficulty
  4. Free hosting options: InfinityFree, 000webhost, Netlify
  5. Choosing the right host for your project

Demonstration

  1. Visit InfinityFree.net and create a free account
  2. Compare control panel features with a paid shared host
  3. Review file manager and database creation tools
  4. Test a live site URL

AI prompts

  1. "Compare shared hosting vs VPS for a beginner PHP MySQL project. Include cost, setup difficulty, and maintenance requirements."
  2. "List 5 free hosting providers that support PHP and MySQL. Rank them by reliability and ease of use for beginners."
  3. "What are the limitations of free hosting providers? How do they affect a production e-commerce website?"

Starter code

<!-- hosting-comparison.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hosting Comparison</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>Hosting Comparison</h1>
    <table>
        <tr>
            <th>Host Type</th>
            <th>Cost</th>
            <th>Control</th>
            <th>Difficulty</th>
        </tr>
        <tr>
            <td>Shared</td>
            <td>$3-10/month</td>
            <td>Low</td>
            <td>Easy</td>
        </tr>
        <tr>
            <td>VPS</td>
            <td>$5-20/month</td>
            <td>High</td>
            <td>Medium</td>
        </tr>
        <tr>
            <td>Free</td>
            <td>$0</td>
            <td>Very Low</td>
            <td>Easy</td>
        </tr>
    </table>
</body>
</html>

Final code

<!-- hosting-comparison.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hosting Comparison</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; margin: 0 auto; padding: 20px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        .recommended { background-color: #e8f5e9; font-weight: bold; }
        .warning { background-color: #fff3e0; }
    </style>
</head>
<body>
    <h1>Hosting Options Comparison</h1>
    <p>Choose the right hosting for your project stage.</p>
    <table>
        <tr>
            <th>Host Type</th>
            <th>Cost</th>
            <th>Control</th>
            <th>Difficulty</th>
            <th>Best For</th>
        </tr>
        <tr class="recommended">
            <td>Shared Hosting</td>
            <td>$3-10/month</td>
            <td>Low</td>
            <td>Easy</td>
            <td>Small business sites, beginners</td>
        </tr>
        <tr>
            <td>VPS</td>
            <td>$5-50/month</td>
            <td>High</td>
            <td>Medium</td>
            <td>Growing sites, developers</td>
        </tr>
        <tr class="warning">
            <td>Free Hosting</td>
            <td>$0</td>
            <td>Very Low</td>
            <td>Easy</td>
            <td>Testing, portfolios, learning</td>
        </tr>
    </table>
</body>
</html>

Exercises

  1. Research three shared hosting providers and list their starter prices.
  2. Sign up for a free hosting account and note the file upload limits.
  3. Compare CPU and RAM specs for two VPS providers.

Homework

  1. Create a decision matrix for hosting providers you would recommend for an e-commerce site. Justify each choice.
  2. Write a 300-word blog post explaining why free hosting is not suitable for a real business.

Quiz

  1. Which hosting type gives you root access to the server?
    • A) Shared hosting
    • B) VPS
    • C) Free hosting
    • D) None
    • Answer: B
  2. What is the main disadvantage of free hosting?
    • A) Fast performance
    • B) No ads
    • C) Limited resources and uptime
    • D) Full control
    • Answer: C
  3. Which host type is best for a complete beginner?
    • A) Dedicated server
    • B) Shared hosting
    • C) Cloud functions
    • D) VPS
    • Answer: B
  4. What does FTP stand for?
    • A) File Transfer Protocol
    • B) Fast Transfer Process
    • C) Front-end Transfer Program
    • D) File Type Protocol
    • Answer: A
  5. Which is a free hosting provider?
    • A) AWS
    • B) InfinityFree
    • C) DigitalOcean
    • D) HostGator
    • Answer: B

Lesson 2: Domain Names and DNS

Instructor notes

Domains are digital addresses. Use the postal address analogy. Emphasize that domains must be registered through ICANN-accredited registrars. Show how to use WHOIS lookup.

Presentation outline

  1. What is a domain name?
  2. How DNS works (simplified)
  3. Domain registration process
  4. DNS record types: A, CNAME, MX, TXT
  5. Connecting domain to hosting

Demonstration

  1. Search for an available domain on Namecheap or GoDaddy
  2. Purchase a domain and review the dashboard
  3. Add an A record pointing to hosting IP
  4. Verify propagation with whatsmyDNS.net

AI prompts

  1. "Explain DNS resolution in simple terms for a 15-year-old. Use an analogy."
  2. "What DNS records are needed to point a domain to InfinityFree hosting? Show the exact values."
  3. "How long does DNS propagation take? What factors affect it?"

Starter code

<?php
// Check if domain resolves to this server
$domain = $_SERVER['HTTP_HOST'];
echo "Current domain: " . $domain;
if ($domain === 'localhost') {
    echo " - Running locally";
} else {
    echo " - Live site";
}
?>

Final code

<?php
// config.php - Environment-aware configuration
$host = $_SERVER['HTTP_HOST'];

// Define environment based on hostname
if (strpos($host, 'localhost') !== false || strpos($host, '127.0.0.1') !== false) {
    define('ENV', 'development');
    define('DB_HOST', 'localhost');
    define('DB_NAME', 'store_dev');
    define('DB_USER', 'root');
    define('DB_PASS', '');
    define('BASE_URL', 'http://localhost/store');
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    define('ENV', 'production');
    define('DB_HOST', 'sqlXXX.infinityfreeapp.com');
    define('DB_NAME', 'epiz_12345678_store');
    define('DB_USER', 'epiz_12345678');
    define('DB_PASS', 'your_password_here');
    define('BASE_URL', 'https://yourdomain.com');
    error_reporting(0);
    ini_set('display_errors', 0);
}

// Create database connection
try {
    $pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    if (ENV === 'development') {
        die("Connection failed: " . $e->getMessage());
    } else {
        die("Database error. Please contact support.");
    }
}
?>

Exercises

  1. Register a free domain from Freenom or purchase a cheap .xyz domain.
  2. Create an A record in your hosting control panel.
  3. Use nslookup or dig to verify your domain resolves to the correct IP.

Homework

  1. Buy a domain name for your final project. Set up DNS records and connect it to your hosting.
  2. Research domain privacy protection. Write a paragraph explaining why it matters.

Quiz

  1. What does DNS stand for?
    • A) Domain Name System
    • B) Data Network Service
    • C) Digital Name Server
    • D) Domain Navigation System
    • Answer: A
  2. Which record type maps a domain to an IP address?
    • A) MX
    • B) CNAME
    • C) A
    • D) TXT
    • Answer: C
  3. How long can DNS propagation take?
    • A) 1 second
    • B) 1 minute
    • C) Up to 48 hours
    • D) 1 week
    • Answer: C
  4. Which is a domain registrar?
    • A) Cloudflare
    • B) Namecheap
    • C) InfinityFree
    • D) Both A and B
    • Answer: D
  5. What is a CNAME record used for?
    • A) Map domain to IP
    • B) Map subdomain to another domain
    • C) Email routing
    • D) Text verification
    • Answer: B

Lesson 3: File Transfer with FTP

Instructor notes

FTP is still widely used despite newer tools like SFTP. FileZilla is the standard free client. Emphasize never storing passwords in plain text.

Presentation outline

  1. What is FTP/SFTP?
  2. FTP clients: FileZilla, WinSCP
  3. Connecting to a server
  4. Uploading and downloading files
  5. File permissions (chmod)
  6. Troubleshooting

Demonstration

  1. Install FileZilla
  2. Create a new site connection with SFTP credentials
  3. Upload index.html to public_html folder
  4. Change file permissions with chmod 644

AI prompts

  1. "What is the difference between FTP, SFTP, and FTPS? Which should a beginner use?"
  2. "Show me how to configure FileZilla to connect to InfinityFree hosting with SFTP."
  3. "What do chmod 644, 755, and 777 mean? When should each be used?"

Starter code

<?php
// file-info.php - Display file permissions info
echo "File Permission Guide\n";
echo "644 = owner read/write, group/others read\n";
echo "755 = owner read/write/execute, group/others read/execute\n";
echo "777 = everyone full access (dangerous!)\n";
?>

Final code

<?php
// deploy-check.php - Verify file permissions after upload
function checkPermissions($file) {
    if (!file_exists($file)) {
        return "File not found";
    }
    $perms = fileperms($file);
    $octal = substr(sprintf('%o', $perms), -4);

    $owner = ($perms & 0x0100) ? 'r' : '-';
    $owner .= ($perms & 0x0080) ? 'w' : '-';
    $owner .= ($perms & 0x0040) ? 'x' : '-';

    $group = ($perms & 0x0020) ? 'r' : '-';
    $group .= ($perms & 0x0010) ? 'w' : '-';
    $group .= ($perms & 0x0008) ? 'x' : '-';

    $others = ($perms & 0x0004) ? 'r' : '-';
    $others .= ($perms & 0x0002) ? 'w' : '-';
    $others .= ($perms & 0x0001) ? 'x' : '-';

    return [
        'octal' => $octal,
        'string' => $owner . $group . $others,
        'safe' => $octal === '0644' || $octal === '0755'
    ];
}

$files = ['index.php', 'config.php', 'uploads/'];
foreach ($files as $file) {
    $result = checkPermissions($file);
    echo "$file: " . $result['string'] . " ($result[octal])\n";
    echo $result['safe'] ? "Safe permissions\n" : "Warning: Check permissions!\n";
}
?>

Exercises

  1. Install FileZilla and connect to your hosting account.
  2. Upload a test file and verify it appears in the public_html folder.
  3. Set file permissions to 644 and 755. Test which pages load correctly.

Homework

  1. Deploy your Module 12 e-commerce project to a free host. Document the steps and any errors.
  2. Create a deployment checklist with at least 10 items.

Quiz

  1. What does FTP stand for?
    • A) File Transfer Protocol
    • B) Fast Transfer Program
    • C) File Type Protocol
    • D) Front-end Transfer Process
    • Answer: A
  2. Which FTP client is free and open source?
    • A) WinSCP
    • B) FileZilla
    • C) Cyberduck
    • D) All of the above
    • Answer: D
  3. What does SFTP stand for?
    • A) Secure File Transfer Protocol
    • B) Simple File Transfer Program
    • C) System File Transfer Protocol
    • D) Standard File Transfer Process
    • Answer: A
  4. What is the recommended permission for PHP files?
    • A) 777
    • B) 644
    • C) 755
    • D) 600
    • Answer: B
  5. Where should public files be uploaded on most shared hosts?
    • A) /private
    • B) /public_html
    • C) /root
    • D) /home
    • Answer: B

Lesson 4: Environment Variables and Configuration

Instructor notes

Hardcoding database credentials is a common beginner mistake. Introduce environment variables as a professional practice. Show how to use getenv() or the vlucas/phpdotenv library.

Presentation outline

  1. What are environment variables?
  2. Development vs production environments
  3. Storing secrets securely
  4. Using .env files
  5. PHP configuration best practices

Demonstration

  1. Create a .env file for local development
  2. Load it with phpdotenv in config.php
  3. Show how getenv('DB_HOST') returns different values
  4. Test that .env is in .gitignore

AI prompts

  1. "Show me how to use vlucas/phpdotenv in a PHP project. Include installation via Composer."
  2. "What information should never be committed to a Git repository?"
  3. "Create a .env.example file for a PHP MySQL e-commerce site with all necessary variables."

Starter code

<?php
// config.php - Hardcoded credentials (BAD PRACTICE)
$db_host = 'localhost';
$db_name = 'store';
$db_user = 'root';
$db_pass = 'password123';

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
?>

Final code

<?php
// config.php - Production-ready configuration
require_once 'vendor/autoload.php';
use Dotenv\Dotenv;

// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Database configuration from environment
$host = getenv('DB_HOST') ?: 'localhost';
$dbname = getenv('DB_NAME') ?: 'store';
$username = getenv('DB_USER') ?: 'root';
$password = getenv('DB_PASS') ?: '';

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password, $options);
} catch(PDOException $e) {
    error_log("Database connection failed: " . $e->getMessage());
    if (getenv('APP_DEBUG') === 'true') {
        die("Connection failed: " . $e->getMessage());
    } else {
        die("Database connection error. Please try again later.");
    }
}

// Application settings
define('APP_NAME', getenv('APP_NAME') ?: 'My Store');
define('APP_URL', getenv('APP_URL') ?: 'http://localhost');
define('APP_DEBUG', getenv('APP_DEBUG') === 'true');
?>
# .env file - NEVER commit this to version control
APP_NAME=My Online Store
APP_URL=http://localhost
APP_DEBUG=true

DB_HOST=localhost
DB_NAME=store
DB_USER=root
DB_PASS=

# Email configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
# .gitignore
vendor/
.env
uploads/
*.log

Exercises

  1. Create a .env file with at least 5 variables for your project.
  2. Load the .env file in PHP and print one variable to the screen.
  3. Add .env to .gitignore and verify Git ignores it.

Homework

  1. Refactor an existing project to use environment variables instead of hardcoded values.
  2. Write a deployment guide that explains how to set environment variables on a live server.

Quiz

  1. What is an environment variable?
    • A) A global JavaScript variable
    • B) A dynamic value outside the application code
    • C) A CSS custom property
    • D) A database column
    • Answer: B
  2. Where should you store database passwords?
    • A) In config.php as plain text
    • B) In a .env file
    • C) In HTML comments
    • D) In JavaScript variables
    • Answer: B
  3. What should .env be added to?
    • A) .gitignore
    • B) composer.json
    • C) index.php
    • D) .htaccess
    • Answer: A
  4. What does APP_DEBUG=true do?
    • A) Deletes errors
    • B) Shows detailed error messages
    • C) Optimizes the database
    • D) Enables HTTPS
    • Answer: B
  5. Which function reads environment variables in PHP?
    • A) $_ENV
    • B) getenv()
    • C) Both A and B
    • D) env()
    • Answer: C

Lesson 5: Going Live - Final Steps

Instructor notes

Launch day is stressful. Emphasize testing everything before going live. Use a checklist approach. Remind students that HTTPS is now mandatory for all sites.

Presentation outline

  1. Pre-launch checklist
  2. Database migration
  3. Enabling HTTPS with Let's Encrypt
  4. Backups and monitoring
  5. Launch and post-launch tasks

Demonstration

  1. Export local database with phpMyAdmin
  2. Import to production database
  3. Enable free SSL with Let's Encrypt in cPanel
  4. Test HTTPS redirect
  5. Create a simple backup script

AI prompts

  1. "Create a 20-item pre-launch checklist for a PHP MySQL website."
  2. "Show me how to export and import a MySQL database using phpMyAdmin."
  3. "How do I enable HTTPS on InfinityFree hosting? What are the steps?"

Starter code

<?php
// backup.php - Simple database backup
$host = 'localhost';
$user = 'root';
$pass = '';
$name = 'store';

$backup_file = 'backup_' . date('Y-m-d') . '.sql';

$command = "mysqldump --host=$host --user=$user --password=$pass $name > $backup_file";
system($command);

echo "Backup created: $backup_file";
?>

Final code

<?php
// backup.php - Production database backup script
require_once 'config.php';

function backupDatabase($host, $username, $password, $database, $output_dir = 'backups/') {
    if (!is_dir($output_dir)) {
        mkdir($output_dir, 0755, true);
    }

    $date = date('Y-m-d_H-i-s');
    $output_file = $output_dir . $database . '_' . $date . '.sql.gz';

    $command = sprintf(
        'mysqldump --host=%s --user=%s --password=%s --single-transaction --routines --triggers %s | gzip > %s',
        escapeshellarg($host),
        escapeshellarg($username),
        escapeshellarg($password),
        escapeshellarg($database),
        escapeshellarg($output_file)
    );

    exec($command, $output, $return_var);

    if ($return_var === 0 && file_exists($output_file)) {
        return [
            'success' => true,
            'file' => $output_file,
            'size' => filesize($output_file)
        ];
    } else {
        return ['success' => false, 'error' => 'Backup failed'];
    }
}

// Create backup
$result = backupDatabase(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($result['success']) {
    echo "Backup created successfully: " . $result['file'] . " (" . formatBytes($result['size']) . ")";
} else {
    echo "Backup failed: " . $result['error'];
}

function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}
?>
<?php
// deploy.php - Deployment helper script
require_once 'config.php';

function runMigrations($pdo) {
    $sql = file_get_contents('database/schema.sql');
    $pdo->exec($sql);
    echo "Database schema updated successfully.\n";
}

function verifyHTTPS() {
    $isHTTPS = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
               || $_SERVER['SERVER_PORT'] == 443;
    if (!$isHTTPS) {
        header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        exit();
    }
}

function checkRequirements() {
    $requirements = [
        'PHP >= 7.4' => version_compare(PHP_VERSION, '7.4.0', '>='),
        'PDO Extension' => extension_loaded('pdo'),
        'MySQL Support' => extension_loaded('pdo_mysql'),
        'Writable uploads/' => is_writable('uploads/'),
        'Config file exists' => file_exists('config.php'),
    ];

    echo "Deployment Check:\n";
    foreach ($requirements as $name => $status) {
        echo $status ? "[PASS] $name\n" : "[FAIL] $name\n";
    }
}

checkRequirements();
?>

Exercises

  1. Export your local database and import it to a remote MySQL server.
  2. Set up Let's Encrypt SSL on your hosting account.
  3. Create a database backup script and schedule it with cron.

Homework

  1. Deploy your final project to a live host. Complete the deployment checklist.
  2. Set up automated daily backups and test restoring from a backup file.

Quiz

  1. What is HTTPS?
    • A) HyperText Transfer Protocol Secure
    • B) HyperText Transfer Protocol Standard
    • C) High Tech Transfer Protocol
    • D) None
    • Answer: A
  2. What does Let's Encrypt provide?
    • A) Web hosting
    • B) Free SSL certificates
    • C) Domain registration
    • D) Email hosting
    • Answer: B
  3. What should you do before going live?
    • A) Delete all test data
    • B) Enable HTTPS
    • C) Backup the database
    • D) All of the above
    • Answer: D
  4. What is a deployment checklist?
    • A) A list of pre-launch tasks
    • B) A server monitoring tool
    • C) A backup schedule
    • D) A cron job list
    • Answer: A
  5. What is database migration?
    • A) Moving a database to another server
    • B) Deleting old records
    • C) Optimizing queries
    • D) Creating indexes
    • Answer: A