3. Install PHP and Create a Simple Form Handler

๐ŸŽฏ Goal

Install PHP on your Ubuntu VM and create a simple web application that processes HTML form submissions, demonstrating basic server-side processing with PHP.

๐Ÿ“‹ Prerequisites

Before beginning this exercise, you should:

๐Ÿ“š Learning Objectives

By the end of this exercise, you will:

๐Ÿ” Why This Matters

In real-world applications, form processing is crucial because:

๐Ÿ“ Step-by-Step Instructions

Step 1: Connect to Your VM

  1. Use SSH to connect to your Ubuntu VM:

    ssh azureuser@<VM_Public_IP>
    

    Replace <VM_Public_IP> with your VM’s actual public IP address.

๐Ÿ’ก Information

  • SSH (Secure Shell): A secure protocol for remotely accessing and managing servers
  • azureuser: The default username created during VM setup
  • Make sure port 22 (SSH) is open in your Network Security Group

Step 2: Install PHP and Required Components

  1. Update the package list to ensure you have the latest information:

    sudo apt update
    
  2. Install PHP, PHP-FPM (FastCGI Process Manager), and commonly needed PHP extensions:

    sudo apt install php-fpm php-cli php-common -y
    
  3. Verify PHP installation and check the version:

    php --version
    
  4. Check that PHP-FPM service is running:

    sudo systemctl status php8.1-fpm
    

๐Ÿ’ก Information

  • PHP-FPM: FastCGI Process Manager that handles PHP requests efficiently
  • php-cli: Command-line interface for PHP, useful for testing
  • php-common: Contains common PHP files and extensions
  • The version number (8.1) may vary depending on your Ubuntu version

โš ๏ธ Common Mistakes

  • Forgetting to update package lists will result in installing outdated packages
  • Not checking service status might leave you unaware if PHP-FPM failed to start

Step 3: Configure Nginx to Process PHP Files

  1. Open the default Nginx configuration file:

    sudo nano /etc/nginx/sites-available/default
    
  2. Replace the existing content with the following configuration:

    server {
        listen 80;
        server_name _;
    
        root /var/www/html;
        index index.php index.html index.htm;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    
  3. Test the Nginx configuration for syntax errors:

    sudo nginx -t
    
  4. If the test is successful, reload Nginx to apply the changes:

    sudo systemctl reload nginx
    

๐Ÿ’ก Information

  • server_name _: Catches all hostnames (wildcard)
  • try_files: Nginx directive that checks for file existence before processing
  • fastcgi_pass: Tells Nginx where to send PHP requests (to PHP-FPM socket)
  • SCRIPT_FILENAME: Parameter that tells PHP which script to execute

Step 4: Test Your PHP Installation

  1. Create a simple PHP info file to verify everything is working:

    sudo nano phpinfo.php
    
  2. Add this content:

    <?php
    phpinfo();
    ?>
    
  3. Set proper permissions for your files:

    sudo chown -R www-data:www-data /var/www/html/
    sudo chmod 644 /var/www/html/*.php
    sudo chmod 644 /var/www/html/*.html
    

Step 5: Create a Welcome Index Page with External CSS

  1. Create the index.html file that references the external CSS:

    sudo nano /var/www/html/index.html
    
  2. Add the following HTML content:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Welcome to Our Website</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="welcome-container">
            <h1>Welcome to Our Website!</h1>
            <p>
                This is a simple web application built with Nginx and PHP on Ubuntu. 
                Our site demonstrates basic form processing and server-side scripting capabilities.
            </p>
            <p>
                Ready to get in touch? Click the button below to access our contact form.
            </p>
            <a href="contact_form.html" class="cta-button">Go to Contact Form</a>
        </div>
    </body>
    </html>
    
  3. First, create a CSS file for styling:

    sudo nano /var/www/html/style.css
    
  4. Add the following CSS content:

    /* General body styling */
    body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: 50px auto;
        padding: 20px;
        background-color: #f5f5f5;
        text-align: center;
    }
    
    /* Welcome container styling */
    .welcome-container {
        background-color: white;
        padding: 40px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    /* Heading styles */
    h1 {
        color: #333;
        margin-bottom: 20px;
    }
    
    /* Paragraph styles */
    p {
        color: #666;
        font-size: 18px;
        line-height: 1.6;
        margin-bottom: 30px;
    }
    
    /* Call-to-action button styling */
    .cta-button {
        display: inline-block;
        background-color: #007bff;
        color: white;
        padding: 15px 30px;
        text-decoration: none;
        border-radius: 5px;
        font-size: 16px;
        font-weight: bold;
        transition: background-color 0.3s;
    }
    
    /* Button hover effect */
    .cta-button:hover {
        background-color: #0056b3;
    }
    

๐Ÿ’ก Information

  • External CSS: Separating styles from HTML follows best practices for maintainability
  • <link rel="stylesheet" href="style.css">: Links the HTML document to the external CSS file
  • CSS Comments: The /* */ syntax helps organize and document your styles
  • Reusable styles: The external CSS can now be used by other pages on your website
  • This approach makes it easier to maintain consistent styling across multiple pages

โœ… Verification Step:

  1. Open your browser and visit http://<VM_Public_IP>/ (just the IP address)
  2. You should see the welcome page with proper styling
  3. Verify the CSS is loading by checking the browser’s developer tools (F12) - there should be no 404 errors for style.css

Step 4: Create a Simple HTML Form

  1. Navigate to the web root directory:

    cd /var/www/html
    
  2. Create an HTML file with a simple form:

    sudo nano contact_form.html
    
  3. Add the following HTML content:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Simple Contact Form</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 600px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f5f5f5;
            }
            .form-container {
                background-color: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            h1 {
                color: #333;
                text-align: center;
            }
            label {
                display: block;
                margin-bottom: 5px;
                font-weight: bold;
                color: #555;
            }
            input[type="text"], input[type="email"], textarea {
                width: 100%;
                padding: 10px;
                margin-bottom: 15px;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box;
            }
            button {
                background-color: #007bff;
                color: white;
                padding: 12px 24px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 16px;
            }
            button:hover {
                background-color: #0056b3;
            }
        </style>
    </head>
    <body>
        <div class="form-container">
            <h1>Contact Us</h1>
            <form action="process_form.php" method="POST">
                <label for="name">Full Name:</label>
                <input type="text" id="name" name="name" required>
    
                <label for="email">Email Address:</label>
                <input type="email" id="email" name="email" required>
    
                <label for="subject">Subject:</label>
                <input type="text" id="subject" name="subject" required>
    
                <label for="message">Message:</label>
                <textarea id="message" name="message" rows="5" required></textarea>
    
                <button type="submit">Send Message</button>
            </form>
        </div>
    </body>
    </html>
    

๐Ÿ’ก Information

  • action=“process_form.php”: Specifies which PHP file will handle the form submission
  • method=“POST”: HTTP method used to send form data securely
  • required: HTML5 attribute that ensures fields are filled before submission
  • CSS styling: Makes the form visually appealing and professional

Step 5: Create the PHP Processing Script

  1. Create a PHP file to handle the form submission:

    sudo nano process_form.php
    
  2. Add the following PHP code:

    <?php
    // Check if the form was submitted using POST method
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
        // Sanitize and collect form data
        $name = htmlspecialchars(trim($_POST['name']));
        $email = htmlspecialchars(trim($_POST['email']));
        $subject = htmlspecialchars(trim($_POST['subject']));
        $message = htmlspecialchars(trim($_POST['message']));
    
        // Get current timestamp
        $submission_time = date('Y-m-d H:i:s');
    
    } else {
        // Redirect to form if accessed directly
        header("Location: contact_form.html");
        exit();
    }
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Submission - Thank You</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                max-width: 600px;
                margin: 50px auto;
                padding: 20px;
                background-color: #f5f5f5;
            }
            .result-container {
                background-color: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .success {
                color: #28a745;
                font-size: 24px;
                text-align: center;
                margin-bottom: 20px;
            }
            .form-data {
                background-color: #f8f9fa;
                padding: 20px;
                border-left: 4px solid #007bff;
                margin: 20px 0;
            }
            .form-data h3 {
                color: #333;
                margin-top: 0;
            }
            .data-item {
                margin-bottom: 10px;
                padding: 5px 0;
                border-bottom: 1px solid #dee2e6;
            }
            .data-label {
                font-weight: bold;
                color: #495057;
            }
            .data-value {
                color: #212529;
                margin-left: 10px;
            }
            .back-link {
                display: inline-block;
                margin-top: 20px;
                padding: 10px 20px;
                background-color: #6c757d;
                color: white;
                text-decoration: none;
                border-radius: 4px;
            }
            .back-link:hover {
                background-color: #545b62;
            }
        </style>
    </head>
    <body>
        <div class="result-container">
            <div class="success">Thank You!</div>
            <p>Your message has been received successfully. Here's a summary of what you submitted:</p>
    
            <div class="form-data">
                <h3>Submission Details</h3>
    
                <div class="data-item">
                    <span class="data-label">Name:</span>
                    <span class="data-value"><?php echo $name; ?></span>
                </div>
    
                <div class="data-item">
                    <span class="data-label">Email:</span>
                    <span class="data-value"><?php echo $email; ?></span>
                </div>
    
                <div class="data-item">
                    <span class="data-label">Subject:</span>
                    <span class="data-value"><?php echo $subject; ?></span>
                </div>
    
                <div class="data-item">
                    <span class="data-label">Message:</span>
                    <span class="data-value"><?php echo nl2br($message); ?></span>
                </div>
    
                <div class="data-item">
                    <span class="data-label">Submitted at:</span>
                    <span class="data-value"><?php echo $submission_time; ?></span>
                </div>
            </div>
    
            <a href="contact_form.html" class="back-link">โ† Send Another Message</a>
        </div>
    </body>
    </html>
    

๐Ÿ’ก Information

  • $_SERVER[“REQUEST_METHOD”]: Checks how the page was accessed (GET vs POST)
  • htmlspecialchars(): Prevents XSS attacks by converting special characters
  • trim(): Removes whitespace from the beginning and end of strings
  • nl2br(): Converts newlines to HTML <br> tags for proper display
  • date(): Gets the current date and time in specified format

โš ๏ธ Common Mistakes

  • Not sanitizing user input can lead to security vulnerabilities
  • Forgetting to check the request method might cause errors when accessing the script directly

โœ… Verification Steps

Test 1: Verify PHP Installation

  1. Open your browser and visit http://<VM_Public_IP>/phpinfo.php
  2. You should see a detailed PHP configuration page showing:
    • PHP version
    • Loaded extensions
    • Configuration settings

Test 2: Test the Contact Form

  1. Open your browser and visit http://<VM_Public_IP>/contact_form.html
  2. Fill out the form with test data:
    • Name: “John Doe”
    • Email: “john.doe@example.com
    • Subject: “Test Message”
    • Message: “This is a test submission”
  3. Click “Send Message”
  4. You should see:
    • A “Thank You!” message
    • All the form data displayed back to you
    • A timestamp showing when the form was submitted

Test 3: Verify Error Handling

  1. Try to access http://<VM_Public_IP>/process_form.php directly
  2. You should be redirected back to the contact form
  3. This confirms that the script properly handles direct access

๐Ÿ”ง Troubleshooting

If the PHP info page doesn’t load:

If the form doesn’t work:

๐Ÿงน Cleanup

  1. Remove the PHP info file for security:

    sudo rm /var/www/html/phpinfo.php
    
  2. The contact form files can remain as they don’t expose sensitive information.

๐Ÿš€ Done!

This tutorial has prepared your environment for more advanced web development.