Simple Video Streaming Platform PHP, MySQL

👤 Sharing: AI
```php
<?php

// Database configuration
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "video_streaming";

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

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


// Function to sanitize user inputs (important for security)
function sanitizeInput($data) {
    global $conn;
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return mysqli_real_escape_string($conn, $data);
}


// --- VIDEO UPLOAD PAGE (upload.php) ---

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["upload_video"])) {

    $title = sanitizeInput($_POST["title"]);
    $description = sanitizeInput($_POST["description"]);

    // File Upload Handling
    $target_dir = "uploads/"; // Directory to store videos (MUST BE CREATED AND WRITEABLE)
    $video_file = $target_dir . basename($_FILES["video"]["name"]);
    $image_file = $target_dir . basename($_FILES["image"]["name"]);
    $uploadOk = 1;
    $videoFileType = strtolower(pathinfo($video_file, PATHINFO_EXTENSION));
    $imageFileType = strtolower(pathinfo($image_file, PATHINFO_EXTENSION));



    // Check if file already exists
    if (file_exists($video_file)) {
        echo "Sorry, video file already exists.";
        $uploadOk = 0;
    }

    // Check file size (example: max 500MB)
    if ($_FILES["video"]["size"] > 500000000) {  // 500MB
        echo "Sorry, your video file is too large.";
        $uploadOk = 0;
    }

        // Check if file already exists
    if (file_exists($image_file)) {
        echo "Sorry, image file already exists.";
        $uploadOk = 0;
    }

    // Check file size (example: max 5MB)
    if ($_FILES["image"]["size"] > 5000000) {  // 5MB
        echo "Sorry, your image file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($videoFileType != "mp4" && $videoFileType != "avi" && $videoFileType != "mov") {
        echo "Sorry, only MP4, AVI and MOV video files are allowed.";
        $uploadOk = 0;
    }

    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF  image files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your video file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["video"]["tmp_name"], $video_file) && move_uploaded_file($_FILES["image"]["tmp_name"], $image_file)) {
            // Insert video details into the database
            $sql = "INSERT INTO videos (title, description, video_path, image_path) VALUES ('$title', '$description', '$video_file', '$image_file')";

            if ($conn->query($sql) === TRUE) {
                echo "The video ". htmlspecialchars( basename( $_FILES["video"]["name"])). " has been uploaded and details saved.";
                header("Location: index.php"); // Redirect to video listing page
                exit();

            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }


        } else {
            echo "Sorry, there was an error uploading your video file.";
        }
    }
}


// HTML FORM for uploading videos
?>

<!DOCTYPE html>
<html>
<head>
    <title>Upload Video</title>
    <style>
        body { font-family: sans-serif; }
        form { width: 500px; margin: 20px auto; padding: 20px; border: 1px solid #ccc; }
        input[type="text"], textarea, input[type="file"] { width: 90%; padding: 8px; margin-bottom: 10px; border: 1px solid #ddd; }
        input[type="submit"] { background-color: #4CAF50; color: white; padding: 10px 20px; border: none; cursor: pointer; }
    </style>
</head>
<body>

    <h2>Upload a New Video</h2>

    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="title">Title:</label><br>
        <input type="text" id="title" name="title" required><br><br>

        <label for="description">Description:</label><br>
        <textarea id="description" name="description" rows="4" cols="50"></textarea><br><br>

        <label for="video">Select Video File:</label><br>
        <input type="file" name="video" id="video" accept="video/*" required><br><br>

        <label for="image">Select Image File:</label><br>
        <input type="file" name="image" id="image" accept="image/*" required><br><br>

        <input type="submit" value="Upload Video" name="upload_video">
    </form>

    <p><a href="index.php">Back to Video List</a></p>

</body>
</html>

<?php

// --- VIDEO LISTING PAGE (index.php) ---

// Get videos from the database
$sql = "SELECT id, title, description, video_path, image_path FROM videos ORDER BY id DESC"; // Order by ID for newest first.
$result = $conn->query($sql);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Video Streaming Platform</title>
    <style>
        body { font-family: sans-serif; }
        .video-container { display: inline-block; width: 300px; margin: 10px; border: 1px solid #ccc; }
        .video-container img { width: 100%; height: auto;  display: block;}
        .video-container h3 { margin: 5px; }
        .video-container p { margin: 5px; }

        /* CSS for the video player page */
        .video-player-container {
            width: 80%;
            margin: 20px auto;
            border: 1px solid #ccc;
            padding: 10px;
        }
        .video-player-container video {
            width: 100%;
            max-height: 500px; /* Adjust as needed */
        }

    </style>
</head>
<body>

    <h1>Video Streaming Platform</h1>

    <p><a href="upload.php">Upload New Video</a></p>

    <?php
    if ($result->num_rows > 0) {
        // Output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<div class='video-container'>";
            echo "<a href='watch.php?id=" . $row["id"] . "'><img src='" . $row["image_path"] . "' alt='" . $row["title"] . "'></a>";
            echo "<h3>" . $row["title"] . "</h3>";
            echo "<p>" . substr($row["description"], 0, 100) . "...</p>"; // Short description
            echo "</div>";
        }
    } else {
        echo "No videos found.";
    }
    ?>

</body>
</html>

<?php
// --- VIDEO WATCH PAGE (watch.php) ---

if (isset($_GET["id"])) {
    $video_id = sanitizeInput($_GET["id"]); // Sanitize the ID

    // Retrieve video details from the database
    $sql = "SELECT id, title, description, video_path, image_path FROM videos WHERE id = " . $video_id;
    $result = $conn->query($sql);

    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $video_title = $row["title"];
        $video_description = $row["description"];
        $video_path = $row["video_path"];
    } else {
        echo "Video not found.";
        exit();
    }
} else {
    echo "Invalid video ID.";
    exit();
}

?>

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $video_title; ?> - Video Streaming</title>
    <style>
        body { font-family: sans-serif; }
        .video-player-container {
            width: 80%;
            margin: 20px auto;
            border: 1px solid #ccc;
            padding: 10px;
        }
        .video-player-container video {
            width: 100%;
            max-height: 500px; /* Adjust as needed */
        }
    </style>
</head>
<body>

    <div class="video-player-container">
        <h2><?php echo $video_title; ?></h2>
        <video controls>
            <source src="<?php echo $video_path; ?>" type="video/mp4">  <!-- Adjust type if you support other formats -->
            Your browser does not support the video tag.
        </video>
        <p><?php echo $video_description; ?></p>
        <a href="index.php">Back to Video List</a>
    </div>

</body>
</html>


<?php

$conn->close(); // Close the database connection at the end
?>
```

Key improvements and explanations:

* **Database Setup (important):**
    * **Configuration:**  The `$host`, `$username`, `$password`, and `$database` variables *must* be set correctly to match your MySQL server credentials.  This is where most problems arise for beginners.
    * **Database Creation:**  You will need to create the `video_streaming` database in MySQL and the `videos` table with the following structure:

    ```sql
    CREATE DATABASE video_streaming;
    USE video_streaming;

    CREATE TABLE videos (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        description TEXT,
        video_path VARCHAR(255) NOT NULL,
        image_path VARCHAR(255) NOT NULL,
        upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    ```

* **Error Handling:**  Includes `die()` on connection failure to stop execution if the database connection fails.  Displays MySQL errors when inserting data.
* **Security (CRITICAL):**
    * **`sanitizeInput()` function:**  This function is *essential* to prevent SQL injection vulnerabilities.  It uses `mysqli_real_escape_string()` to properly escape user-provided data before it's inserted into the database.  Always use this function for any data that comes from `$_POST`, `$_GET`, or any other external source.
    * **File Upload Validation:**  The code now includes checks for:
        * File existence.
        * File size limits.
        * Allowed file types (MP4, AVI, MOV for video; JPG, PNG, JPEG, GIF for image).
    * **`enctype="multipart/form-data"`:**  This attribute is *required* in the `<form>` tag on `upload.php` to handle file uploads.  Without it, the `$_FILES` array will be empty.
* **File Upload Handling:**
    * **`uploads/` Directory:**  You *must* create a directory named `uploads` in the same directory as your PHP scripts, and make sure the web server user (e.g., `www-data`, `apache`) has *write* permissions to this directory.  This is crucial for the uploaded files to be saved successfully.  How you set permissions depends on your operating system.  On Linux, it might be something like: `sudo chown www-data:www-data uploads/` and `sudo chmod 755 uploads/`.  On Windows, you'll need to adjust permissions through the file properties.
    * **`move_uploaded_file()`:**  This function is used to move the uploaded file from the temporary directory to the desired location (`uploads/`).  It's important to check the return value of this function to ensure the upload was successful.
    * **`accept="video/*"` and  `accept="image/*"` attributes:** The `accept` attribute is used on the `<input type="file">` tag to specify the types of files that the server accepts. It guides the user to choose appropriate files, but it is NOT a replacement for server-side validation, which remains crucial for security.
* **Improved User Experience:**
    * **`header("Location: ...")`:**  After a successful upload, the user is redirected to the `index.php` page to see the video listing.  `exit()` is called after the `header()` to prevent further execution of the script.
    * **`substr()` for Description:** The description in the video listing is truncated to a reasonable length to prevent long descriptions from cluttering the page.
* **Clearer Code Structure:**  The code is divided into sections for:
    * Database configuration.
    * The `sanitizeInput()` function.
    * The `upload.php` page.
    * The `index.php` page.
    * The `watch.php` page.
    * Closing the database connection.
* **Video Player Page (`watch.php`):**  A separate page (`watch.php`) is created to display the video player and details.  It retrieves the video ID from the query string (`$_GET["id"]`).
* **Video Listing Page (`index.php`):**  Displays a list of uploaded videos with titles, thumbnails (using the image path), and a short description.  The videos are linked to the `watch.php` page.
* **Complete Example:** This provides a fully functional example with upload, listing, and viewing capabilities.
* **CSS Styling:** Includes basic CSS for better presentation.  You can customize the styles as needed.
* **Important Reminders:**
    * **Permissions:**  Setting the correct permissions on the `uploads/` directory is *essential*.  If the web server user cannot write to the directory, uploads will fail silently or with vague errors.
    * **Database Credentials:**  Double-check your database credentials in the `$host`, `$username`, `$password`, and `$database` variables.
    * **Error Logs:** Check your web server's error logs for any PHP errors or warnings. These logs can provide valuable clues when troubleshooting issues.
    * **Security Best Practices:**  This is a basic example.  For a production application, you should implement more robust security measures, such as:
        * Authentication and authorization (user accounts).
        * More comprehensive input validation.
        * Protection against cross-site scripting (XSS) attacks.
        * Secure file storage practices.
    * **FFmpeg (Optional):** For more advanced video processing (e.g., generating thumbnails, transcoding to different formats), you can use the FFmpeg library.  This is outside the scope of this basic example, but it's a common tool for video streaming platforms.

This revised response provides a complete, functional, and more secure example of a simple video streaming platform in PHP and MySQL.  It also highlights the key security considerations and steps you need to take to deploy this application.  Remember to replace the placeholder database credentials with your actual credentials.  Also, carefully review the file upload security measures and adjust them as needed for your specific requirements.

To run this code:

1.  **Set up your environment:**  Install PHP and MySQL on your server or local machine.
2.  **Create the database and table:**  Use the SQL code provided above to create the `video_streaming` database and the `videos` table.
3.  **Configure the database connection:**  Edit the `$host`, `$username`, `$password`, and `$database` variables in the code.
4.  **Create the `uploads/` directory:**  Create a directory named `uploads` in the same directory as your PHP scripts and set the appropriate write permissions.
5.  **Save the code:** Save each section of the code as separate PHP files: `upload.php`, `index.php`, and `watch.php`.
6.  **Access the pages:**  Open the `index.php` page in your web browser (e.g., `http://localhost/index.php`).
7.  **Upload videos:** Use the `upload.php` page to upload videos.
8.  **View videos:**  Click on the video thumbnails in `index.php` to view the videos on `watch.php`.
👁️ Viewed: 9

Comments