# cPanel Shared Hosting Deployment Guide

**Version:** 2.0 (Production Ready)
**Last Updated:** 2025-12-26
**Package:** dashboard-cpanel-production.tar.gz

---

## 📦 What's Included

**Production-ready package with:**
- ✅ Clean codebase (no test files)
- ✅ Merged SQL schema (all migrations included)
- ✅ Optimized autoloader
- ✅ Production .htaccess files
- ✅ Security hardening
- ✅ Middleware (RateLimiter, Auth)
- ✅ Essential documentation only

---

## 🚀 Quick Deployment (10 Minutes)

### Step 1: Upload Package

1. Login to **cPanel**
2. Go to **File Manager**
3. Navigate to `public_html/`
4. Upload `dashboard-cpanel-production.tar.gz`
5. Extract the archive
6. Rename extracted folder to `dashboard`

```
public_html/
└── dashboard/          ← Your application root
    ├── public/         ← Dashboard UI
    ├── src/            ← Application logic
    ├── bootstrap/      ← Initialization
    ├── config/         ← Configuration
    └── .env.example    ← Configuration template
```

---

### Step 2: Create Database

1. Go to **cPanel → MySQL® Databases**
2. Create database: `username_dashboard`
3. Create user: `username_dbuser`
4. Set strong password
5. Add user to database with **ALL PRIVILEGES**
6. Note down credentials:
   ```
   Database: username_dashboard
   User: username_dbuser
   Password: [your_password]
   Host: localhost
   ```

---

### Step 3: Import Database Schema

**Option A: phpMyAdmin**
1. Go to **cPanel → phpMyAdmin**
2. Select database `username_dashboard`
3. Click **Import** tab
4. Choose file: `dashboard/database-setup.sql`
5. Click **Go**
6. Wait for success message

**Option B: Command Line (if available)**
```bash
mysql -u username_dbuser -p username_dashboard < public_html/dashboard/database-setup.sql
```

**Verify:**
```sql
SHOW TABLES;
-- Should show: domains, activity_logs, settings, shortlinks, users, etc.
```

---

### Step 4: Configure Environment

1. Go to **File Manager → dashboard/**
2. Copy `.env.example` to `.env`
3. Edit `.env` with File Editor:

```ini
# Database
DB_HOST=localhost
DB_NAME=username_dashboard
DB_USER=username_dbuser
DB_PASS=your_database_password

# cPanel API
CPANEL_HOST=server123.yourhostingprovider.com
CPANEL_USERNAME=your_cpanel_username
CPANEL_API_TOKEN=your_cpanel_api_token
CPANEL_PORT=2083

# Cloudflare API (optional)
CLOUDFLARE_EMAIL=your@email.com
CLOUDFLARE_API_KEY=your_cloudflare_global_api_key

# Server
SERVER_IP=your_server_ip_address

# Application
APP_ENV=production
```

4. **Save** the file
5. Set permissions: **600** (read/write owner only)

---

### Step 5: Set Document Root

**Option A: Addon Domain (Recommended)**
1. Go to **cPanel → Domains**
2. Click **Create A New Domain**
3. Domain: `dashboard.yourdomain.com`
4. Document Root: `/home/username/public_html/dashboard/public`
5. Uncheck "Share document root"
6. Click **Submit**

**Option B: Subdomain**
1. Go to **cPanel → Subdomains**
2. Subdomain: `dashboard`
3. Domain: `yourdomain.com`
4. Document Root: `/home/username/public_html/dashboard/public`
5. Click **Create**

**Important:** Document root MUST point to `/public` folder, NOT `/dashboard` root!

---

### Step 6: Configure PHP Settings

1. Go to **cPanel → MultiPHP INI Editor**
2. Select domain: `dashboard.yourdomain.com`
3. Set these values:

```ini
display_errors = Off
max_execution_time = 300
memory_limit = 256M
post_max_size = 40M
upload_max_filesize = 40M
session.cookie_httponly = On
session.cookie_secure = On
session.use_strict_mode = On
```

4. Click **Apply**

---

### Step 7: Enable OPcache (Performance)

**Create `.user.ini` in dashboard root:**
```bash
# Via File Manager, create: dashboard/.user.ini
```

**Content:**
```ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=0
opcache.validate_timestamps=0
opcache.fast_shutdown=1
```

**Set permissions:** 644

---

### Step 8: Install SSL Certificate

1. Go to **cPanel → SSL/TLS Status**
2. Find `dashboard.yourdomain.com`
3. Click **Run AutoSSL**
4. Wait for certificate installation
5. Verify: Visit `https://dashboard.yourdomain.com`

**Or use Let's Encrypt:**
1. Go to **cPanel → SSL/TLS**
2. Click **Manage SSL sites**
3. Install certificate for `dashboard.yourdomain.com`

---

### Step 9: Test Installation

**Health Check:**
```
https://dashboard.yourdomain.com
```

**Expected:**
- ✅ Dashboard loads without errors
- ✅ HTTPS padlock shows
- ✅ No PHP errors displayed
- ✅ Login page appears (if auth enabled)

**If you see errors:**
- Check `.env` file configuration
- Check database connection
- Check file permissions (755 folders, 644 files)
- Check error logs in cPanel

---

### Step 10: Create Admin User (First Time)

**Via phpMyAdmin:**
```sql
INSERT INTO users (email, password_hash, full_name, role, status, created_at)
VALUES (
    'admin@yourdomain.com',
    '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', -- password: password
    'Admin User',
    'admin',
    'active',
    NOW()
);
```

**⚠️ Change password immediately after first login!**

---

## 🔒 Security Hardening

### Protect .env File

Create `dashboard/.htaccess` (if not exists):
```apache
<Files ".env">
    Order allow,deny
    Deny from all
</Files>

<Files "*.sql">
    Order allow,deny
    Deny from all
</Files>
```

### Force HTTPS

Edit `dashboard/public/.htaccess`, uncomment:
```apache
# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```

### Block Access to Vendor

Add to `dashboard/.htaccess`:
```apache
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^vendor/ - [F,L]
</IfModule>
```

---

## 📁 cPanel File Structure

```
/home/username/
├── public_html/
│   └── dashboard/                  ← Application root
│       ├── .env                    ← Environment config (PROTECT THIS!)
│       ├── .htaccess               ← Root security rules
│       ├── .user.ini               ← PHP settings
│       ├── database-setup.sql      ← Merged database schema
│       ├── composer.json           ← Dependencies
│       ├── bootstrap/              ← App initialization
│       ├── config/                 ← Configuration helpers
│       ├── src/                    ← Application code
│       │   ├── Middleware/         ← RateLimiter, Auth
│       │   ├── Repository/         ← Database access
│       │   ├── Service/            ← Business logic
│       │   └── Integration/        ← cPanel, Cloudflare APIs
│       ├── public/                 ← PUBLIC DOCUMENT ROOT
│       │   ├── index.php           ← Dashboard UI
│       │   ├── .htaccess           ← Public security rules
│       │   └── ajax/               ← API endpoints
│       ├── user-dashboard/         ← User interface
│       ├── vendor/                 ← Composer dependencies
│       └── logs/                   ← Application logs (create if needed)
│
└── redirect/                       ← Shortlink handler (separate)
    ├── s.php                       ← Redirect handler
    ├── shim.php                    ← Shim page
    └── .htaccess                   ← Clean URL rules
```

---

## 🔧 Post-Deployment Configuration

### Configure Redirect Handler

1. Create addon domain: `go.yourdomain.com`
2. Document root: `/home/username/redirect`
3. Upload redirect files from package
4. Create wildcard subdomain: `*.yourdomain.com` → `/home/username/redirect`

### Test Domain Management

1. Login to dashboard
2. Go to **Domains** tab
3. Add test domain: `example.com`
4. Verify:
   - ✅ Domain added to cPanel
   - ✅ Wildcard subdomain created
   - ✅ DNS record added to Cloudflare (if configured)
   - ✅ Database record created

### Test Shortlink Creation

1. Go to **Shortlinks** tab
2. Create test shortlink:
   - Destination: `https://google.com`
   - Title: `Test Link`
   - Domain: Select from dropdown
3. Verify:
   - ✅ Shortlink created
   - ✅ Redirect works: `https://go.yourdomain.com/slug`
   - ✅ Click tracking works

---

## 📊 Monitoring

### Check Logs

**cPanel Error Log:**
```
cPanel → Errors → Error Log
```

**Application Log:**
```
dashboard/logs/php-error.log
```

**Apache Error Log:**
```
cPanel → Metrics → Errors
```

### Performance Monitoring

1. Go to **cPanel → CPU and Concurrent Connection Usage**
2. Monitor resource usage
3. Check for spikes

### Database Monitoring

1. Go to **cPanel → phpMyAdmin**
2. Check table sizes
3. Monitor slow queries

---

## 🐛 Troubleshooting

### "500 Internal Server Error"

**Cause:** PHP error, missing dependencies, permission issues

**Fix:**
```bash
# Check error log
tail -f dashboard/logs/php-error.log

# Check file permissions
chmod 755 dashboard/
chmod 644 dashboard/.env
chmod 755 dashboard/public/

# Verify .htaccess
cat dashboard/public/.htaccess
```

### "Database connection failed"

**Cause:** Wrong credentials in `.env`

**Fix:**
```bash
# Test connection
mysql -u username_dbuser -p username_dashboard

# If fails, recreate user in cPanel
# Update .env with correct credentials
```

### "CSRF token invalid"

**Cause:** Session issues, missing session folder

**Fix:**
```bash
# Check session settings
php -i | grep session

# Verify session.save_path writable
```

### "Rate limit exceeded"

**Cause:** Too many requests from same IP

**Fix:**
```bash
# Whitelist your IP in Mini WAF
# Or increase rate limit in RateLimiter.php
```

---

## 🔄 Updates & Maintenance

### Updating Application

1. Backup current files
2. Backup database
3. Upload new package
4. Extract and overwrite
5. Keep `.env` file (don't overwrite!)
6. Clear OPcache:
   ```php
   <?php opcache_reset(); echo "Cache cleared"; ?>
   ```
7. Test functionality

### Database Migrations

If new migrations:
```bash
mysql -u username_dbuser -p username_dashboard < new-migration.sql
```

### Clearing Caches

**OPcache:**
```bash
# Create clear-cache.php in public/
<?php
opcache_reset();
echo "OPcache cleared";
```

**APCu (if installed):**
```bash
<?php
apcu_clear_cache();
echo "APCu cleared";
```

---

## ✅ Deployment Checklist

- [ ] Package uploaded and extracted
- [ ] Database created
- [ ] Database schema imported (database-setup.sql)
- [ ] `.env` file configured
- [ ] Document root set to `/public` folder
- [ ] PHP settings configured
- [ ] SSL certificate installed
- [ ] Dashboard accessible via HTTPS
- [ ] Admin user created
- [ ] Test domain added
- [ ] Test shortlink created
- [ ] Redirect handler working
- [ ] Error logs checked
- [ ] Performance optimized (OPcache enabled)
- [ ] Backups configured

---

## 🆘 Support

**Application Logs:**
```
dashboard/logs/php-error.log
```

**cPanel Support:**
Contact your hosting provider

**Documentation:**
- `README.md` - Overview
- `PRODUCTION_CHECKLIST.md` - Complete checklist
- `SECURITY_IMPROVEMENTS.md` - Security audit

---

## 📝 Important Notes

1. **Never commit `.env` to version control**
2. **Always backup before updates**
3. **Monitor logs regularly**
4. **Use strong passwords**
5. **Keep software updated**
6. **Enable HTTPS always**
7. **Restrict file permissions properly**
8. **Test on staging before production**

---

**Deployment completed? You're ready to manage domains and shortlinks! 🎉**

**Last Updated:** 2025-12-26
