W3docs

How to let PHP to create subdomain automatically for each user?

To automatically create a subdomain for each user in PHP, you can use the following steps:

To automatically create a subdomain for each user in PHP, you can use the following steps:

  1. Create a form for users to sign up for an account on your website.
  2. In the form submission handler, validate the user's input to ensure it contains only valid subdomain characters (alphanumeric and hyphens). Extract the desired subdomain string using substr() and store the user along with their subdomain in a database.
  3. Configure your DNS provider to use a wildcard record (*.yourdomain.com) pointing to your server's IP address. Note: PHP's dns_get_record() only queries existing DNS records; it cannot create them. To manage DNS programmatically, use your DNS provider's official API.
  4. Configure your web server to route all subdomain requests to a single entry point (e.g., index.php). For Nginx, add a server_name directive with a wildcard:
    server {
        listen 80;
        server_name *.yourdomain.com yourdomain.com;
        root /var/www/html;
        index index.php;
        # ... other config ...
    }
    For Apache, use a wildcard ServerAlias in your virtual host configuration.
  5. In your PHP application, read the $_SERVER['HTTP_HOST'] variable to identify the requested subdomain, then query your database to find the associated user and serve their content.
  6. Send an email to the user with their subdomain name and a link to their new subdomain.
<?php
// Note: In a production application, separate user registration and request routing into different endpoints.
// Database setup (example)
$pdo = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8mb4', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Schema: CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50), subdomain VARCHAR(50) UNIQUE);

// 1. Validate and sanitize subdomain input
$username = preg_replace('/[^a-z0-9-]/i', '', $_POST['username']);
$subdomain = strtolower(substr($username, 0, 20));

// 2. Check if subdomain is available in the database
$stmt = $pdo->prepare("SELECT id FROM users WHERE subdomain = ?");
$stmt->execute([$subdomain]);
if ($stmt->rowCount() > 0) {
    die("Subdomain already taken.");
}

// 3. Insert user and subdomain into database
$stmt = $pdo->prepare("INSERT INTO users (username, subdomain) VALUES (?, ?)");
$stmt->execute([$username, $subdomain]);

// 4. Route logic: identify requested subdomain from HTTP_HOST
$currentHost = $_SERVER['HTTP_HOST'];
// Use parse_url to safely handle ports (e.g., subdomain.example.com:8080)
$hostWithoutPort = parse_url($currentHost, PHP_URL_HOST);
$parts = explode('.', $hostWithoutPort);
// Extracts the first segment, which correctly identifies the subdomain regardless of TLD depth (e.g., co.uk)
$requestedSubdomain = $parts[0] ?? '';

// Distinguish base domain from subdomains to avoid routing conflicts
$baseDomain = 'yourdomain.com';
if ($hostWithoutPort === $baseDomain || count($parts) < 3) {
    // Handle base domain or invalid subdomain
    die("Please access via a valid subdomain.");
}

// Fetch user data based on $requestedSubdomain and render page
$stmt = $pdo->prepare("SELECT username FROM users WHERE subdomain = ?");
$stmt->execute([$requestedSubdomain]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
    // Dynamically load user-specific content
    echo "Welcome, " . htmlspecialchars($user['username']) . "! Your subdomain is active.";
} else {
    die("User not found for this subdomain.");
}
?>

You will need to have permissions to modify your DNS and web server configurations, as well as have knowledge about DNS and web server routing. It is also a good practice to validate user input for security reasons, and to have a mechanism for removing subdomains if necessary.