# LAMP Stack Essentials: Setting Up Apache, MySQL, and PHP on Ubuntu

Creating a LAMP (Linux, Apache, MySQL, PHP) stack project involves setting up a web server environment where PHP-based web applications can run smoothly. Below, I will provide a sample project along with detailed installation steps. This example will include:

1. **Apache Server** - To serve PHP files.
    
2. **MySQL Database** - To store and manage data.
    
3. **PHP** - For web application development.
    

---

### **Prerequisites**

1. **A Linux server** (Ubuntu/CentOS recommended).
    
2. Root or sudo access to the server.
    
3. A domain name or IP address for your server.
    
4. Basic knowledge of Linux, MySQL, and PHP.
    

---

### **Step 1: Install the LAMP Stack**

#### **1.1 Update System Packages**

```plaintext
sudo apt update
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732359836795/b1780f68-0270-4736-adb6-9725907372d5.png align="center")

#### **1.2 Install Apache**

```plaintext
sudo apt install apache2 -y
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732359943991/4b3db250-7bef-4072-a570-51b608761f92.png align="center")

Verify installation by visiting [`http://your-server-ip`](http://your-server-ip) in a browser.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360006749/8ddfc8e2-ff82-4643-b9e6-6be15a907757.png align="center")

#### **1.3 Install MySQL**

```plaintext
sudo apt install mysql-server -y
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360088984/e1ec82c1-7326-4628-8eba-04061616832c.png align="center")

Set a strong password for the root user and follow the prompts.

```plaintext
sudo mysql_secure_installation
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360153715/d203a097-36d5-49bb-935f-c193fc34f75c.png align="center")

#### **1.4 Install PHP**

```plaintext
sudo apt install php libapache2-mod-php php-mysql -y
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360231588/a6696600-14af-443e-a716-d2142bda9171.png align="center")

Check the PHP version:

```plaintext
php -v
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360259223/ca1f5f39-55ef-4470-92a3-f8de8fecd93f.png align="center")

#### **1.5 Restart Apache**

```plaintext
sudo systemctl restart apache2
sudo systemctl status apache2
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360310441/d3eb155e-f90a-4ab6-84b9-c147bb96e596.png align="center")

---

### **Step 2: Set Up the MySQL Database**

#### **2.1 Log into MySQL**

```plaintext
sudo mysql -u root -p
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360367422/f09acd6e-1478-429a-8363-0a61872b534a.png align="center")

#### **2.2 Create a Database and User**

```plaintext
CREATE DATABASE blog;
CREATE USER 'bloguser'@'localhost' IDENTIFIED BY 'strongpassword';
GRANT ALL PRIVILEGES ON blog.* TO 'bloguser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360471738/b64bee23-a239-44dc-a9ca-746b02e0af48.png align="center")

---

### **Step 3: Configure Apache for Your Blog**

#### **3.1 Create a Virtual Host**

Create a new configuration file:

```plaintext
sudo nano /etc/apache2/sites-available/blog.conf
```

Add the following content:

```plaintext
<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /var/www/html/blog
    <Directory /var/www/html/blog>
        AllowOverride All
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/blog_error.log
    CustomLog ${APACHE_LOG_DIR}/blog_access.log combined
</VirtualHost>
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360575470/24fbe6c6-6fd5-41cc-9989-a020647ffc5d.png align="center")

Enable the virtual host and Apache rewrite module:

```plaintext
sudo a2ensite blog.conf
sudo a2enmod rewrite
sudo systemctl restart apache2
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360634957/0084533f-0a80-44d0-a2be-230dab936ffc.png align="center")

---

### **Step 4: Build the Blog Application**

#### **4.1 Create Blog Directory**

```plaintext
sudo mkdir -p /var/www/html/blog
sudo chown -R $USER:$USER /var/www/html/blog
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360673221/23fa79db-0864-40ca-abfa-6d4e238a87fd.png align="center")

#### **4.2 Create Blog PHP Files**

1. **Database Connection (**`nano /var/www/html/blog/db.php`)
    

```plaintext
<?php
$servername = "localhost";
$username = "bloguser";
$password = "strongpassword";
$dbname = "blog";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360731967/cb7a4040-5e5c-4ed5-9b69-a4be4bff3244.png align="center")

2. **Blog Post Submission (**`submit_post.php`)
    

```plaintext
<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = $_POST['title'];
    $content = $_POST['content'];

    $sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";

    if ($conn->query($sql) === TRUE) {
        echo "New post created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
}
?>
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361296587/3a63333f-2b11-4234-b296-939f84b7c281.png align="center")

3. **Main Blog Page (**`index.php`)
    

```plaintext
<?php
include 'db.php';

$sql = "SELECT * FROM posts";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>My Blog</title>
</head>
<body>
    <h1>My Blog</h1>
    <form action="submit_post.php" method="post">
        <input type="text" name="title" placeholder="Title" required><br>
        <textarea name="content" placeholder="Write your blog post here..." required></textarea><br>
        <button type="submit">Post</button>
    </form>
    <h2>All Posts</h2>
    <?php while($row = $result->fetch_assoc()): ?>
        <h3><?php echo $row['title']; ?></h3>
        <p><?php echo $row['content']; ?></p>
        <hr>
    <?php endwhile; ?>
</body>
</html>
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361350318/b4a532b0-0871-4dc6-9661-952837febe2b.png align="center")

---

### **Step 5: Initialize the Database Table**

#### **5.1 Create the Posts Table**

Log into MySQL and run:

```plaintext
USE blog;

CREATE TABLE posts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732360910824/175b45a4-29b5-4d94-8bfe-9ba52504c646.png align="center")

---

### **Step 6: Access Your Blog**

* Visit your server’s IP or domain in a browser:
    
    ```plaintext
    http://your-server-ip/blog
    ```
    
* Create and view blog posts dynamically.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361404129/69bd2563-fa54-411e-b7cf-685f0ad23ae3.png align="center")

---

### **Step 7: Secure Your Application**

1. **Enable HTTPS** using Let's Encrypt:
    

```plaintext
sudo apt install certbot python3-certbot-apache -y
sudo certbot --apache
```

### **Step 7: Automate Backup using Script**

The script performs three main tasks:

1. **Backup the Web Server Configuration:** The script will create a compressed archive of the Apache web server configuration from `/etc/apache2`.
    
2. **Backup the Application Server Configuration:** The script will backup your application server's configuration (in this example, the blog’s configuration stored at `/var/www/html/blog`).
    
3. **Backup the Database:** Using `mysqldump`, the script will back up the blog’s database into a `.sql` file.
    

Here's the script:

```plaintext
#!/bin/bash

# Set date format for backup filenames
DATE=$(date +"%Y-%m-%d_%H-%M-%S")

# Directories for backups
WEB_SERVER_CONFIG="/etc/apache2"
APP_SERVER_CONFIG="/var/www/html/blog"
DB_BACKUP_DIR="/backup/db"
WEB_BACKUP_DIR="/backup/web"
APP_BACKUP_DIR="/backup/app"

# Database credentials
DB_USER="bloguser"
DB_PASSWORD="Linux@123#"
DB_NAME="blog"
DB_HOST="localhost"

# Backup functions
tar -czf $WEB_BACKUP_DIR/web_server_config_$DATE.tar.gz -C $WEB_SERVER_CONFIG . && echo "Web config backup complete."
tar -czf $APP_BACKUP_DIR/app_server_config_$DATE.tar.gz -C $APP_SERVER_CONFIG . && echo "App config backup complete."
mysqldump -u $DB_USER -p$DB_PASSWORD -h $DB_HOST $DB_NAME > $DB_BACKUP_DIR/db_backup_$DATE.sql && echo "Database backup complete."

echo "Backup process completed successfully."
```

**Step 3: Breakdown of the Script**

* **Date Format:** The `DATE` variable stores the current date and time in the format `YYYY-MM-DD_HH-MM-SS`, which helps in creating unique filenames for each backup.
    
* **Backup Directories:** The script defines variables for the directories where each type of backup will be stored:
    
    * Web server config backups are stored in `$WEB_BACKUP_DIR`.
        
    * Application server config backups are stored in `$APP_BACKUP_DIR`.
        
    * Database backups are stored in `$DB_BACKUP_DIR`.
        
* **Backup Commands:**
    
    * `tar` is used to compress the configuration files into `.tar.gz` archives.
        
    * `mysqldump` is used to dump the MySQL database into a `.sql` file.
        

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732359655312/f4f43ea7-7312-4977-bc9b-771acfa37632.png align="center")

**Step 4: Running the Script** To run the script:

1. Save it to a file, for example, `backup_`[`script.sh`](http://script.sh).
    
2. Make the script executable:
    
    ```plaintext
    chmod +x backup_script.sh
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361600875/f0081046-4740-49a2-a9e1-972c8e172300.png align="center")
    
3. Execute the script:
    
    ```plaintext
    ./backup_script.sh
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361756749/35704082-6aca-4201-ac7f-bd7484640dea.png align="center")
    
4. Verify the backup files
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1732361838762/f568df9d-f673-4ae6-b4b5-fe1f43d166c5.png align="center")

**Step 5: Automating the Backup Process** To ensure regular backups, you can schedule this script to run automatically using `cron`:

1. Open the crontab file:
    
    ```plaintext
    crontab -e
    ```
    
2. Add a line to run the script at your desired frequency (e.g., daily at midnight):
    
    ```plaintext
    0 0 * * * /path/to/backup_script.sh
    ```
