skip to Main Content

Am trying to send a file and it’s record via webhook to another website which receives the data but am having problem saving the file to a directory am having unkknown error what could the cause be any alternative I can try? This is my log result I logged all the records and file for clarity `

[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
                    November 27, 2023 => 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
        )

)

And this is my code


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);
?>


Could the problem be from the data received via webhook or my code? Please review I was supposed to save the file to a directory along side it’s records to db. Please help alternative code will do to thanks.

2

Answers


  1. Chosen as BEST ANSWER

    Yeah you're almost correct @CBroe I was sending the file as json text data instead of handling it as a file just seeing your suggestion but I've fixed this since yesterday. The file is supposed to be sent as a file not as text which I did unintentionally am supposed to specify the it as a file, get the file data and send this data across. I fixed it by modifying my code like this // Create cURL file object $file = new CURLFile($xfile['tmp_name'], $xfile['type'], $xfile['name']); This way I was able to send the file via json webhook instead of sending it as a text format which it's not. Thanks guys.


  2. cut bellow lines:

    // 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);
    

    paste upper$insertMailStmt->execute(); line. the result should be:

    // 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search