Secure Digital Vault PHP, MySQL

👤 Sharing: AI
```php
<?php

// Database connection details
$host = "localhost"; // Or your database host
$username = "root"; // Or your database username
$password = ""; // Or your database password
$database = "digital_vault"; // The name of your database

// Create connection
$conn = new mysqli($host, $username, $password, $database);

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

// Function to sanitize user input (important for security!)
function sanitize_input($data) {
    global $conn;
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return mysqli_real_escape_string($conn, $data); // Crucial for preventing SQL injection
}

// ---  File Upload and Storage ---

// Process file upload (handle in a separate form or within the same form)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["uploaded_file"])) {

    $upload_dir = "uploads/"; // Directory to store uploaded files.  MUST EXIST and be writable by the webserver!
    $filename = basename($_FILES["uploaded_file"]["name"]); // Original filename
    $target_file = $upload_dir . $filename; // Full path to the uploaded file

    // Sanitize the filename (IMPORTANT!)
    $filename = sanitize_input($filename);
    $target_file = $upload_dir . $filename;

    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file already exists (optional, but recommended)
    if (file_exists($target_file)) {
        echo "<p style='color: red;'>Sorry, file already exists.</p>";
        $uploadOk = 0;
    }

    // Check file size (optional, but recommended) - adjust as needed
    if ($_FILES["uploaded_file"]["size"] > 5000000) {  //5MB limit
        echo "<p style='color: red;'>Sorry, your file is too large.</p>";
        $uploadOk = 0;
    }

    // Allow certain file formats (optional, but recommended) - customize as needed
    $allowed_formats = array("jpg", "jpeg", "png", "gif", "pdf", "txt", "doc", "docx"); // Add more as needed
    if (!in_array($fileType, $allowed_formats)) {
        echo "<p style='color: red;'>Sorry, only JPG, JPEG, PNG, GIF, PDF, TXT, DOC, DOCX files are allowed.</p>";
        $uploadOk = 0;
    }

    // If $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "<p style='color: red;'>Sorry, your file was not uploaded.</p>";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["uploaded_file"]["tmp_name"], $target_file)) {
            echo "<p style='color: green;'>The file ". htmlspecialchars( $filename ). " has been uploaded.</p>";

            // Store file information in the database

            // Get other form data, sanitize it
            $description = sanitize_input($_POST["file_description"]); // Assume you have a description field
            $category = sanitize_input($_POST["file_category"]); // Assume you have a category field
            $date_uploaded = date("Y-m-d H:i:s"); // Current timestamp

            $sql = "INSERT INTO files (filename, filepath, description, category, date_uploaded)
                    VALUES ('$filename', '$target_file', '$description', '$category', '$date_uploaded')";

            if ($conn->query($sql) === TRUE) {
                echo "<p style='color: green;'>File information saved to database.</p>";
            } else {
                echo "<p style='color: red;'>Error saving file information: " . $conn->error . "</p>";
            }


        } else {
            echo "<p style='color: red;'>Sorry, there was an error uploading your file.</p>";
        }
    }
}


// --- Display Files ---
function display_files() {
    global $conn;

    $sql = "SELECT id, filename, description, category, date_uploaded FROM files ORDER BY date_uploaded DESC"; // Order by most recent
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        echo "<h2>Available Files</h2>";
        echo "<table border='1'>";
        echo "<tr><th>Filename</th><th>Description</th><th>Category</th><th>Uploaded</th><th>Action</th></tr>";
        while($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . htmlspecialchars($row["filename"]) . "</td>"; // Sanitize output!
            echo "<td>" . htmlspecialchars($row["description"]) . "</td>"; // Sanitize output!
            echo "<td>" . htmlspecialchars($row["category"]) . "</td>"; // Sanitize output!
            echo "<td>" . htmlspecialchars($row["date_uploaded"]) . "</td>"; // Sanitize output!
            echo "<td><a href='uploads/" . urlencode($row["filename"]) . "' target='_blank'>Download</a> |
                  <a href='delete.php?id=" . $row["id"] . "'>Delete</a></td>"; // Example delete link
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p>No files found.</p>";
    }
}



?>

<!DOCTYPE html>
<html>
<head>
    <title>Secure Digital Vault</title>
</head>
<body>

    <h1>Secure Digital Vault</h1>

    <h2>Upload File</h2>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" enctype="multipart/form-data">
        Select file to upload:
        <input type="file" name="uploaded_file" id="uploaded_file">
        <br><br>
        Description: <input type="text" name="file_description"><br><br>
        Category: <input type="text" name="file_category"><br><br>
        <input type="submit" value="Upload File" name="submit">
    </form>

    <hr>

    <?php display_files(); ?>

</body>
</html>

<?php
// Close connection
$conn->close();
?>
```

Key improvements and explanations:

* **Security (Crucial):**
    * **`sanitize_input()` function:**  This is the *most important* part.  It's *essential* to sanitize all user inputs to prevent SQL injection attacks.  `mysqli_real_escape_string()` is the correct way to escape strings for use in MySQL queries when using `mysqli`.  **Never trust user input.**
    * **`htmlspecialchars()` for output:** When displaying data from the database (or anywhere user input might be present), use `htmlspecialchars()` to prevent cross-site scripting (XSS) attacks.  This converts special characters (like `<` and `>`) to their HTML entities, preventing them from being interpreted as code.
    * **File Upload Security:**  The code includes checks for file size, file type, and existing files.  It's crucial to configure your web server to prevent execution of uploaded files (e.g., prevent `.php` files from being run).  See the notes on server configuration below.
    * **Using `urlencode()`:** When creating the download link, `urlencode()` is used on the filename.  This ensures that special characters in the filename are properly encoded for use in a URL.
* **Error Handling:** Improved error messages when file uploads fail or database queries fail.
* **Database Interaction:**
    * Uses `mysqli` for database interaction, which is the preferred method for newer PHP versions.
    * Includes database connection error handling.
    * The code now properly inserts the file information into the `files` table.
    * Includes a `date_uploaded` column to track when files were uploaded.
* **File Management:**
    * **`uploads/` directory:** You **must** create this directory in the same location as your PHP script and make it writable by the web server user (e.g., `www-data`, `apache`, or `nobody`). The script will *not* work without this directory and proper permissions.
    * Uses `move_uploaded_file()` to securely move the uploaded file from the temporary directory to the destination directory.
* **Code Structure:**
    * The code is organized into functions (`sanitize_input()`, `display_files()`) to improve readability and maintainability.
    * Clear comments explain each section of the code.
* **HTML Form:** Includes a simple HTML form for uploading files.  The `enctype="multipart/form-data"` attribute is *essential* for file uploads.  Also added input fields for description and category.
* **Displaying Files:** The `display_files()` function retrieves file information from the database and displays it in a table.  The "Download" link allows users to download the uploaded files.
* **Delete Functionality (Basic):**  The display table includes a "Delete" link.  This links to a separate `delete.php` file (which you'll need to create; example given below).
* **Important Considerations for Production:**
    * **Authentication:**  This is a *very basic* example.  In a real-world application, you would need to implement user authentication and authorization to ensure that only authorized users can upload and access files.
    * **Encryption:**  For truly secure storage, you should encrypt the files on the server.  PHP offers various encryption libraries.  Consider using a strong encryption algorithm like AES.
    * **Database Security:** Follow best practices for securing your MySQL database, including strong passwords, limiting user privileges, and keeping the database software up to date.
    * **Regular Backups:**  Implement a robust backup strategy to protect your data from loss.
    * **Logging:** Log all file uploads, downloads, and deletions for auditing purposes.
    * **Server Configuration:** Configure your web server to prevent the execution of uploaded files.  This is usually done by setting the `php_admin_flag engine off;` directive within the `uploads/` directory's configuration in your web server (e.g., Apache or Nginx).  Consult your web server's documentation for details.  This is *critical* to prevent malicious users from uploading and executing PHP code on your server.
    * **Content Security Policy (CSP):** Implement a CSP to further mitigate XSS attacks.
* **Example `delete.php` (Create this file in the same directory):**

```php
<?php
// delete.php

// Database connection details (same as in the main script)
$host = "localhost";
$username = "root";
$password = "";
$database = "digital_vault";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

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


// Sanitize input (VERY IMPORTANT!)
function sanitize_input($data) {
    global $conn;
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return mysqli_real_escape_string($conn, $data);
}



if (isset($_GET['id'])) {
    $id = sanitize_input($_GET['id']); // Sanitize the ID!

    // Get the filepath from the database before deleting
    $sql_select = "SELECT filepath, filename FROM files WHERE id = '$id'";
    $result = $conn->query($sql_select);

    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $filepath = $row['filepath'];
        $filename = $row['filename'];


        // Delete the database record
        $sql_delete = "DELETE FROM files WHERE id = '$id'";

        if ($conn->query($sql_delete) === TRUE) {
            // Attempt to delete the actual file from the filesystem
            if (unlink($filepath)) {
                echo "<p style='color: green;'>File deleted successfully.</p>";
            } else {
                echo "<p style='color: orange;'>Database record deleted, but failed to delete the file from the server.  Check file permissions.</p>";
            }


        } else {
            echo "<p style='color: red;'>Error deleting record: " . $conn->error . "</p>";
        }

    } else {
        echo "<p style='color: red;'>File not found.</p>";
    }

    // Redirect back to the main page
    header("Location: " . $_SERVER['HTTP_REFERER']); // Redirect back to the page the user was on
    exit; // Ensure that no further code is executed after the redirect
} else {
    echo "<p style='color: red;'>Invalid request.</p>";
}

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

Key improvements in `delete.php`:

* **Security:**  Sanitizes the `id` parameter from the URL using the `sanitize_input()` function.
* **File Deletion:**  Attempts to delete the actual file from the file system using `unlink()`.  This is important to remove the file data from the server completely. **Important:**  The web server user needs write permissions to the `uploads/` directory for this to work.
* **Error Handling:** Includes error messages if the file is not found in the database or if the deletion fails.
* **Redirection:**  Redirects the user back to the main page after the deletion is complete.
* **Retrieving filepath from database:** The script *now* retrieves the `filepath` from the database before attempting to delete the file. This is essential to ensure the correct file is deleted and to prevent potential security vulnerabilities. *Also retrieves the filename*

**To run this code:**

1.  **Create a database:** Create a MySQL database named `digital_vault`.
2.  **Create a table:** Create a table named `files` with the following structure:

    ```sql
    CREATE TABLE files (
        id INT AUTO_INCREMENT PRIMARY KEY,
        filename VARCHAR(255) NOT NULL,
        filepath VARCHAR(255) NOT NULL,
        description TEXT,
        category VARCHAR(255),
        date_uploaded DATETIME
    );
    ```
3.  **Create the `uploads/` directory:** Create a directory named `uploads` in the same directory as your PHP script.  **Make sure the web server user (e.g., `www-data`, `apache`, or `nobody`) has write permissions to this directory.**  This is *essential*.  On Linux, you might need to run a command like `sudo chown www-data:www-data uploads` and `sudo chmod 755 uploads`.  Consult your operating system and web server documentation for specific instructions.
4.  **Save the code:** Save the PHP code as a `.php` file (e.g., `index.php`).  Save the `delete.php` file in the same directory.
5.  **Configure your web server:** Configure your web server to serve the PHP file.  This usually involves creating a virtual host or modifying the existing web server configuration. *VERY IMPORTANT - follow the instructions about preventing the execution of php files in the `uploads/` directory!*
6.  **Access the script:** Open the PHP file in your web browser (e.g., `http://localhost/index.php`).

This revised response provides a much more secure and complete example of a digital vault.  Remember to always prioritize security when handling user-uploaded files.  Consult security experts for a production-ready system.
👁️ Viewed: 9

Comments