通过 Webhook 上传文件时出现未知错误

问题描述 投票:0回答:1

我正在尝试发送一个文件,并通过 webhook 将其记录到另一个接收数据的网站,但在将文件保存到目录时遇到问题,出现未知错误,我可以尝试的替代方案是什么?这是我的日志结果,为了清楚起见,我记录了所有记录和文件`

[24-Nov-2023 13:28:25 America/New_York] Webhook Data Received: {"emails":[{"email":"[email protected]","mail_id":"657070","date":"2023-11-24","time":"13:28:25","file_path":"\/home\/darksbqo\/public_html\/apps\/dragonphly\/files\/file_657070_1700850505_8631.pdf"}],"xfile":{"name":"ckeditor4-export-pdf.pdf","type":"application\/pdf","tmp_name":"\/tmp\/phpwTZwba","error":0,"size":21075}}

2023-11-24 13:28:25 - Webhook Data Received: 
Array
(
    [emails] => Array
        (
            [0] => Array
                (
                    [email] => [email protected]
                    [mail_id] => 657070
                    [date] => 2023-11-24
                    [time] => 13:28:25
                    [file_path] => /home/darksbqo/public_html/apps/dragonphly/files/file_657070_1700850505_8631.pdf
                )

        )

    [xfile] => Array
        (
            [name] => ckeditor4-export-pdf.pdf
            [type] => application/pdf
            [tmp_name] => /tmp/phpwTZwba
            [error] => 0
            [size] => 21075
        )

)

[24-Nov-2023 13:28:25 America/New_York] Error moving uploaded file: ckeditor4-export-pdf.pdf. Error code: Unknown, Error message: Unknown error
Error moving uploaded file: ckeditor4-export-pdf.pdf. Error code: Unknown, Error message: Unknown error[24-Nov-2023 13:28:25 America/New_York] Webhook Response: {"success":false,"message":"Email(s) processed successfully","errors":["Error moving uploaded file: ckeditor4-export-pdf.pdf. Error code: Unknown, Error message: Unknown error","Error inserting record into mails table: Column 'file_path' cannot be null"]}

Webhook Response: 
Array
(
    [success] => 
    [message] => Email(s) processed successfully
    [errors] => Array
        (
            [0] => Error moving uploaded file: ckeditor4-export-pdf.pdf. Error code: Unknown, Error message: Unknown error
            [1] => Error inserting record into mails table: Column 'file_path' cannot be null
        )

)

这是我的代码


text/x-generic webhook.php ( PHP script text )

<?php
// Set error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
ini_set('error_log', __DIR__ . '/webhook_log.txt');

// Create a database connection
$servername = "servername  is here";
$username = "username is here";
$password = "password is here";
$dbname = "mailgateway";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Log the raw webhook data for debugging
$rawWebhookData = file_get_contents('php://input');
error_log("Webhook Data Received: " . $rawWebhookData);

// Receive and decode webhook data
$webhookData = json_decode($rawWebhookData, true);

// Check if decoding was successful
if ($webhookData === null) {
    // Log the error
    $jsonLastError = json_last_error();
    $jsonLastErrorMessage = json_last_error_msg();
    $logMessage = "Error decoding webhook data. Error code: $jsonLastError, Message: $jsonLastErrorMessage";
    error_log($logMessage);

    // Output a generic error to the response for debugging
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'An error occurred while processing the webhook data.']);
    exit; // Stop execution
}

// Initialize response array
$response = ['success' => true, 'message' => 'Email(s) processed successfully', 'errors' => []];

// Prepare and bind the SQL statement for inserting into 'mails' table
$insertMailStmt = $conn->prepare("INSERT INTO mails (email, mail_id, file_path, date, time) VALUES (?, ?, ?, ?, ?)");
$insertMailStmt->bind_param("sssss", $email, $mailId, $filePath, $date, $time);

// Log the processed data and errors to webhook_log.txt
$logFile = __DIR__ . '/webhook_log.txt';
$logMessage = PHP_EOL . date('Y-m-d H:i:s') . ' - Webhook Data Received: ' . PHP_EOL . print_r($webhookData, true) . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);

try {
    // Start a database transaction
    $conn->begin_transaction();

    // Process each email data
    foreach ($webhookData['emails'] as $emailData) {
        // Extract data and sanitize
        $email = filter_var($emailData['email'], FILTER_SANITIZE_EMAIL);
        $mailId = filter_var($emailData['mail_id'], FILTER_SANITIZE_STRING);
        $date = filter_var($emailData['date'], FILTER_SANITIZE_STRING);
        $time = filter_var($emailData['time'], FILTER_SANITIZE_STRING);

        // Upload  file
        $xfile = $webhookData['xfile']; // Adjust this based on your payload structure
        $filename = 'file_' . $mailId . '_' . time() . '_' . rand(1000, 9999) . '.pdf';  // Adjust the extension accordingly
        $xfilePath = $_SERVER['DOCUMENT_ROOT'] . '/data/uploads/files/' . $filename;

        // Move the payload file to the specified directory
        if (move_uploaded_file($xfile['tmp_name'], $xfilePath)) {
            $filePath = $xfilePath; // Set the file path to the uploaded path
        } else {
            // Log the error details if available
            $errorMessage = error_get_last()['message'] ?? 'Unknown error';
            $errorCode = error_get_last()['type'] ?? 'Unknown';

            // Check if error details are available before logging
            if ($errorMessage !== null && $errorCode !== null) {
                $logMessage = "Error moving uploaded file: " . basename($xfile['name']) . ". Error code: $errorCode, Error message: $errorMessage";
                error_log($logMessage);
                file_put_contents($logFile, $logMessage, FILE_APPEND);
            } else {
                // Log a generic error message if detailed information is not available
                $logMessage = "Error moving uploaded file: " . basename($xfile['name']) . ". Unknown error occurred during file move.";
                error_log($logMessage);
                file_put_contents($logFile, $logMessage, FILE_APPEND);
            }

            // Add error to the response
            $response['success'] = false;
            $response['errors'][] = $logMessage;
        }

        // Bind parameters and execute the prepared statement
        $insertMailStmt->execute();

        // Check for successful insertion
        if ($insertMailStmt->affected_rows <= 0) {
            $response['success'] = false;
            $response['errors'][] = "Error inserting record into mails table: " . $insertMailStmt->error;
        }
    }

    // Commit the database transaction
    $conn->commit();
} catch (Exception $e) {
    // Rollback the transaction in case of an exception
    $conn->rollback();

    // Log the exception
    $logMessage = "Exception: " . $e->getMessage();
    error_log($logMessage);
    file_put_contents($logFile, $logMessage, FILE_APPEND);

    // Add error to the response
    $response['success'] = false;
    $response['errors'][] = $logMessage;
} finally {
    // Close the prepared statement
    $insertMailStmt->close();
}

// Log the response
error_log("Webhook Response: " . json_encode($response));
file_put_contents($logFile, PHP_EOL . 'Webhook Response: ' . PHP_EOL . print_r($response, true), FILE_APPEND);

// Output the response
header('Content-Type: application/json');
echo json_encode($response);
?>


问题可能出在通过 webhook 或我的代码接收到的数据吗?请查看我应该将文件保存到数据库记录旁边的目录中。请帮助替代代码,谢谢。

php file-upload webhooks
1个回答
0
投票

剪掉下面的线:

// Prepare and bind the SQL statement for inserting into 'mails' table
$insertMailStmt = $conn->prepare("INSERT INTO mails (email, mail_id, file_path, date, time) VALUES (?, ?, ?, ?, ?)");
$insertMailStmt->bind_param("sssss", $email, $mailId, $filePath, $date, $time);

粘贴上

$insertMailStmt->execute();
线。结果应该是:

// Prepare and bind the SQL statement for inserting into 'mails' table
$insertMailStmt = $conn->prepare("INSERT INTO mails (email, mail_id, file_path, date, time) VALUES (?, ?, ?, ?, ?)");
$insertMailStmt->bind_param("sssss", $email, $mailId, $filePath, $date, $time);
// Bind parameters and execute the prepared statement
$insertMailStmt->execute();
© www.soinside.com 2019 - 2024. All rights reserved.