开发者问题收集

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

2023-11-25
144

我尝试通过 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 或我的代码收到的数据上吗?请检查我应该将文件保存到目录中,并将其记录保存到数据库中。请帮忙提供替代代码,谢谢。

2个回答

是的,你几乎是对的@CBroe,我将文件作为 json 文本数据发送,而不是将其作为文件处理,只是看到了你的建议,但我从昨天开始就修复了这个问题。该文件应该作为文件发送,而不是作为文本发送,我无意中这样做了,应该将其指定为文件,获取文件数据并发送这些数据。我通过修改代码来修复它,如下所示 // 创建 cURL 文件对象 $file = new CURLFile($xfile['tmp_name'], $xfile['type'], $xfile['name']); 这样,我就能够通过 json webhook 发送文件,而不是将其作为文本格式发送,而它不是。谢谢大家。

Freeman
2023-11-27

剪切以下行:

// 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();
Erfun
2023-11-25