Search code examples
phpperl

How to send asynchronous json using Perl to an PHP url?


I am trying to send some data in json format with POST to a specific url test.php. The request should be asynchronous , I need to get the http response code if the data is sent or not (I don't wont to wait until the request is done processed on test.php).

I have built a perl function to send the data

#!/usr/bin/perl

use strict;
use warnings;
use JSON qw(encode_json);
use AnyEvent;
use AnyEvent::HTTP;


=pod
Function send asynchronus data , get response code 
=cut
sub sendOutboundPostRequestAsync {
    my ($url, $data, $token) = @_;

    # Create a condition variable to wait for the asynchronous request
    my $request_done = AnyEvent->condvar;

    # Convert the data hash to JSON
    my $json_data = encode_json($data);
    print "JSON data being sent: $json_data\n";  # For debugging

    # Make the HTTP POST request asynchronously
    http_post $url,
        headers => {
            'Authorization' => $token,
            'Content-Type'  => 'application/json',
        },
        body => $json_data,
        sub {
            my ($body, $headers) = @_;
            my $status_code = $headers->{Status} // 500;  # Default to 500 if no status
            
            # Print the response for debugging
            print "Response Body: $body\n";
            print "Request completed with status code: $status_code\n";

            # Send the status code back through the condition variable
            $request_done->send($status_code);
        };

    return $request_done;  # Return the condition variable for further processing
}


#####
my $url = 'http://xxx.xxx.xxx/test.php';
my $token = 'eyJ0eXAiOiJKV1QiLCJhbGci'; 

# Example data to send
my %data = (
    uniqueid => '1727331196.gesti',
    start_time => '2024-09-26 08:13:17',
);

# Call the function
my $response_code_condvar = sendOutboundPostRequestAsync($url, \%data, $token);
my $response_code         = $response_code_condvar->recv;  # Wait for the request to complete

print "Final Response Code: $response_code\n";

The php code (shortened for testing purpose) to get the data

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
    
// Retrieve the raw POST data
$postData = file_get_contents('php://input');

// Log all headers for debugging
$headers = getallheaders();
file_put_contents('postData.txt', "Received Headers:\n" . print_r($headers, true) . "\n", FILE_APPEND);

// Specify the file path
$file_path = 'postData.txt';

// Open the file for writing (append mode)
$file = fopen($file_path, 'a'); // Use 'w' to overwrite the file
  
// Write the POST data to the file
fwrite($file, "Received POST data:\n" . $postData . "\n\n");
    
// Close the file
fclose($file);  

// Decode the JSON data
$data = json_decode($postData, true);

// Check if data decoding was successful
if ($data === null) {
    // Handle error: Invalid JSON
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

// Extract the action from the decoded data
$action = $data['action'] ?? null;

// Check if the action is set
if ($action === null) {
    // Handle error: Missing action
    http_response_code(400);
    echo 'Missing action';
    exit;
}   
?>

Issue

After executing the Perl script I get

ast1:~ # perl test.agi
JSON data being sent: {"start_time":"2024-09-26 08:13:17","uniqueid":"1727331196.gesti"}
Response Body: Invalid JSON
Request completed with status code: 400
Final Response Code: 400

The data seems correct and it should be sent without issue, but on the PHP side on the text log I get

Received POST data:
headers

Desired output

Received POST data:
{
    "start_time": "2024-09-26 08:13:17",
    "uniqueid": "1727331196.gesti"
}

Questions

  1. Is this the best way to send asynchronous data using Perl ?
  2. What could be the issue of an empty result of data ?

Solution

  • You're doing

    http_post $url, headers => {...}, body => $json_data, sub {... }
    

    but that doesn't match the signature in the documentation, which says

    http_post $url, $body, key => value..., $cb->($data, $headers)
    

    That is, the body is the second argument, and isn't passed as a key-value pair. Since you got the order wrong, it's interpreting headers as the body, and mixing up everything else.

    So if you want to use http_post (rather than http_request) with your example, it would be

    http_post $url, $json_data, headers => { ... }, sub { ... }