Generate HTML file from HTML form

Learn generate html file from html form with practical examples, diagrams, and best practices. Covers php, html, templates development techniques with visual explanations.

Dynamically Generate HTML Files from Form Submissions with PHP

Hero image for Generate HTML file from HTML form

Learn how to capture user input from an HTML form and programmatically generate a new, personalized HTML file on your server using PHP.

Generating dynamic HTML files from user input is a powerful technique for creating personalized content, reports, or custom pages. This article will guide you through the process of building an HTML form, processing its submission with PHP, and then using that data to construct and save a new HTML file on your server. We'll cover the essential PHP functions and best practices for secure and efficient file generation.

Understanding the Workflow: Form to File

The core idea involves a user filling out a form, submitting it to a PHP script, and that script taking the submitted data to write a new HTML file. This process can be broken down into several key stages: form creation, data submission, server-side processing, and file generation. It's crucial to handle each stage carefully, especially input validation, to prevent security vulnerabilities and ensure data integrity.

flowchart TD
    A[User Fills HTML Form] --> B{Form Submission (POST)};
    B --> C[PHP Script Receives Data];
    C --> D{Validate & Sanitize Input};
    D -- Valid --> E[Construct HTML Content];
    E --> F[Write HTML Content to File];
    F --> G[Server Saves .html File];
    G --> H[Redirect/Display Success];
    D -- Invalid --> I[Display Error/Re-render Form];

Workflow for generating an HTML file from a form submission.

Step 1: Creating the HTML Form

First, you need an HTML form to collect the user's data. This form will use the POST method to send data to a PHP script. For this example, let's create a simple form that asks for a title and some content for a new page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate HTML Page</title>
    <style>
        body { font-family: sans-serif; margin: 2em; background-color: #f4f4f4; }
        form { background: white; padding: 2em; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); max-width: 600px; margin: auto; }
        label { display: block; margin-bottom: 0.5em; font-weight: bold; }
        input[type="text"], textarea { width: 100%; padding: 0.8em; margin-bottom: 1em; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        textarea { resize: vertical; min-height: 100px; }
        button { background-color: #007bff; color: white; padding: 0.8em 1.5em; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; }
        button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <form action="generate_page.php" method="post">
        <h1>Create Your Custom Page</h1>
        <label for="pageTitle">Page Title:</label>
        <input type="text" id="pageTitle" name="pageTitle" required>

        <label for="pageContent">Page Content:</label>
        <textarea id="pageContent" name="pageContent" required></textarea>

        <button type="submit">Generate Page</button>
    </form>
</body>
</html>

Step 2: Processing with PHP and Generating the File

The generate_page.php script will receive the form data, sanitize it, construct the HTML content, and then use PHP's file handling functions to write this content to a new .html file. It's crucial to sanitize user input to prevent Cross-Site Scripting (XSS) and other injection attacks. We'll use htmlspecialchars() for basic escaping.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 1. Sanitize and validate input
    $pageTitle = isset($_POST['pageTitle']) ? htmlspecialchars($_POST['pageTitle'], ENT_QUOTES, 'UTF-8') : 'Untitled Page';
    $pageContent = isset($_POST['pageContent']) ? htmlspecialchars($_POST['pageContent'], ENT_QUOTES, 'UTF-8') : 'No content provided.';

    // Basic validation
    if (empty(trim($pageTitle)) || empty(trim($pageContent))) {
        die("Error: Page title and content cannot be empty.");
    }

    // 2. Define the filename and path
    // Create a URL-friendly filename from the title
    $filename = strtolower(str_replace(' ', '-', preg_replace('/[^a-zA-Z0-9\s]/', '', $pageTitle)));
    $filename = substr($filename, 0, 50); // Limit filename length
    $filename = "pages/{$filename}.html";

    // Ensure the 'pages' directory exists
    if (!is_dir('pages')) {
        mkdir('pages', 0755, true);
    }

    // 3. Construct the HTML content for the new file
    $htmlContent = "<!DOCTYPE html>\n";
    $htmlContent .= "<html lang=\"en\">\n";
    $htmlContent .= "<head>\n";
    $htmlContent .= "    <meta charset=\"UTF-8\">\n";
    $htmlContent .= "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n";
    $htmlContent .= "    <title>{$pageTitle}</title>\n";
    $htmlContent .= "    <style>\n";
    $htmlContent .= "        body { font-family: sans-serif; margin: 2em; line-height: 1.6; background-color: #f9f9f9; color: #333; }\n";
    $htmlContent .= "        .container { max-width: 800px; margin: auto; background: white; padding: 2em; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }\n";
    $htmlContent .= "        h1 { color: #007bff; }\n";
    $htmlContent .= "    </style>\n";
    $htmlContent .= "</head>\n";
    $htmlContent .= "<body>\n";
    $htmlContent .= "    <div class=\"container\">\n";
    $htmlContent .= "        <h1>{$pageTitle}</h1>\n";
    $htmlContent .= "        <p>{$pageContent}</p>\n";
    $htmlContent .= "        <hr>
";
    $htmlContent .= "        <small>Generated on " . date('Y-m-d H:i:s') . "</small>\n";
    $htmlContent .= "    </div>\n";
    $htmlContent .= "</body>\n";
    $htmlContent .= "</html>";

    // 4. Write the content to the file
    if (file_put_contents($filename, $htmlContent) !== false) {
        // 5. Success: Redirect to the newly created page or display a success message
        $generatedUrl = str_replace(' ', '%20', basename($filename)); // Handle spaces in URL if any
        header("Location: {$generatedUrl}");
        exit();
    } else {
        die("Error: Could not write to file '{$filename}'. Check directory permissions.");
    }
} else {
    // If accessed directly without POST data
    header("Location: index.html");
    exit();
}

?>

Deployment and Permissions

For this setup to work, your web server (e.g., Apache, Nginx) needs write permissions to the directory where you intend to save the generated HTML files. In our example, this is the pages/ directory. You might need to adjust file permissions using chmod on your server. For instance, chmod 755 pages/ would grant the necessary permissions while maintaining security.

1. Create index.html

Save the HTML form code provided in Step 1 as index.html in your web server's document root (e.g., htdocs for Apache, www for Nginx).

2. Create generate_page.php

Save the PHP script provided in Step 2 as generate_page.php in the same directory as index.html.

3. Create pages directory

Create a new directory named pages in the same location. This is where your generated HTML files will be stored.

4. Set Directory Permissions

Ensure your web server has write permissions to the pages directory. On Linux/Unix, you might run chmod 755 pages/ from your terminal in the parent directory.

5. Access the Form

Open http://localhost/index.html (or your server's equivalent URL) in your web browser, fill out the form, and submit it. A new HTML file should be generated and displayed.