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:
- Have completed the previous VM creation exercises
- Have an Ubuntu VM running with Nginx installed
- Be able to SSH into your VM
- Understand basic HTML form structure
๐ Learning Objectives
By the end of this exercise, you will:
- Install PHP and PHP-FPM on Ubuntu to enable server-side processing
- Configure Nginx to work with PHP for dynamic content
- Create an HTML form that collects user input
- Implement a PHP script that processes form data and displays results
- Understand the request-response cycle between client and server
๐ Why This Matters
In real-world applications, form processing is crucial because:
- It enables user interaction and data collection
- It’s the foundation for user registration, contact forms, and feedback systems
- It demonstrates the separation between presentation (HTML) and logic (PHP)
- It will be foundational for database integration we’ll build later
๐ Step-by-Step Instructions
Step 1: Connect to Your VM
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
Update the package list to ensure you have the latest information:
sudo apt updateInstall PHP, PHP-FPM (FastCGI Process Manager), and commonly needed PHP extensions:
sudo apt install php-fpm php-cli php-common -yVerify PHP installation and check the version:
php --versionCheck 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
Open the default Nginx configuration file:
sudo nano /etc/nginx/sites-available/defaultReplace 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; } }Test the Nginx configuration for syntax errors:
sudo nginx -tIf 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
Create a simple PHP info file to verify everything is working:
sudo nano phpinfo.phpAdd this content:
<?php phpinfo(); ?>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
Create the index.html file that references the external CSS:
sudo nano /var/www/html/index.htmlAdd 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>First, create a CSS file for styling:
sudo nano /var/www/html/style.cssAdd 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:
- Open your browser and visit
http://<VM_Public_IP>/(just the IP address)- You should see the welcome page with proper styling
- 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
Navigate to the web root directory:
cd /var/www/htmlCreate an HTML file with a simple form:
sudo nano contact_form.htmlAdd 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
Create a PHP file to handle the form submission:
sudo nano process_form.phpAdd 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
- Open your browser and visit
http://<VM_Public_IP>/phpinfo.php - You should see a detailed PHP configuration page showing:
- PHP version
- Loaded extensions
- Configuration settings
Test 2: Test the Contact Form
- Open your browser and visit
http://<VM_Public_IP>/contact_form.html - Fill out the form with test data:
- Name: “John Doe”
- Email: “john.doe@example.com”
- Subject: “Test Message”
- Message: “This is a test submission”
- Click “Send Message”
- 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
- Try to access
http://<VM_Public_IP>/process_form.phpdirectly - You should be redirected back to the contact form
- This confirms that the script properly handles direct access
๐ง Troubleshooting
If the PHP info page doesn’t load:
- Check that PHP-FPM is running:
sudo systemctl status php8.1-fpm - Verify Nginx configuration:
sudo nginx -t - Check error logs:
sudo tail -f /var/log/nginx/error.log
If the form doesn’t work:
- Ensure file permissions are correct
- Check that both HTML and PHP files are in
/var/www/html/ - Verify the file names match exactly
๐งน Cleanup
Remove the PHP info file for security:
sudo rm /var/www/html/phpinfo.phpThe contact form files can remain as they don’t expose sensitive information.
๐ Done!
This tutorial has prepared your environment for more advanced web development.