Untitled

 avatar
unknown
plain_text
11 days ago
2.4 kB
1
Indexable
<?php
// Include the database connection
include('../db/db_connection.php'); // Ensure the path is correct

define('UPLOAD_DIR', '../pages/uploads/');
define('ALLOWED_EXTENSIONS', ['jpg', 'jpeg', 'png', 'gif']);
define('MAX_FILE_SIZE', 2 * 1024 * 1024); // 2MB limit

if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true); // Ensure the folder exists, or create it
}

if (isset($_FILES['ImagePath']) && $_FILES['ImagePath']['error'] === UPLOAD_ERR_OK) {
    $file_info = pathinfo($_FILES["ImagePath"]["name"]);
    $file_extension = strtolower($file_info['extension']);
    
    // Validate file extension and size
    if (in_array($file_extension, ALLOWED_EXTENSIONS) && $_FILES['ImagePath']['size'] <= MAX_FILE_SIZE) {
        // Sanitize Student_id
        $student_id = preg_replace('/[^a-zA-Z0-9_]/', '', $_POST['student_id']);
        
        // Check if student_id is not empty after sanitization
        if (empty($student_id)) {
            die("Invalid student ID.");
        }

        // Create a unique filename to prevent overwriting
        $ImagePath = UPLOAD_DIR . $student_id . '.' . $file_extension;
        $relativePath = 'uploads/' . $student_id . '.' . $file_extension; // Store relative path

        // Move file to the target directory
        if (move_uploaded_file($_FILES["ImagePath"]["tmp_name"], $ImagePath)) {
            echo "File uploaded successfully.";

            // Update the database (Use SQLSRV functions for MSSQL)
            $sql = "UPDATE tbl_students SET ImagePath = ? WHERE student_id = ?";
            $params = [$relativePath, $student_id];
            $stmt = sqlsrv_prepare($conn, $sql, $params);

            if ($stmt) {
                if (sqlsrv_execute($stmt)) {
                    echo "Database updated successfully.";
                    header("Location: ../pages/studentprofile.php");
                    exit;
                } else {
                    echo "Failed to update the database.";
                }
            } else {
                echo "Error preparing statement.";
            }
        } else {
            echo "Failed to move the uploaded file.";
        }
    } else {
        echo "Invalid file type or size. Allowed types: " . implode(", ", ALLOWED_EXTENSIONS) . ". Max size: 2MB.";
    }
}
?>
Leave a Comment