Coverting CURL command to CURL php

258 Views Asked by At

I am trying to add documents to elastic search index via bulk API. My CURL query works fine on command line and I converted it to PHP.

When I am trying to run PHP code, nothing happens. Neither documents are added in index in elastic search, nor any error appears.

CURL Query:

curl -H "Content-Type:application/json" -XPOST "http://localhost:9200/inven/default/_bulk?pretty" --data-binary "@file_name.json"

PHP Query:

 $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $post = array(
        'file' => '@' .realpath('file_name.json')
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_POST, 1);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);

I have set ini_set('max_execution_time', 0); as well, in case it, it was timing out. What could be the issue?

3

There are 3 best solutions below

1
On BEST ANSWER

You are not sending the actual file contents, just its filename as a string. Try this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:9200/inven/default/_bulk?pretty');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1 );

// The line below assumes the file_name.json is located in the same directory
// with this script, if not change the path to the file with the correct one.
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('file_name.json') );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
0
On

If you are using PHP 5.5+, use:

$post = [
    'file' => curl_file_create('file_name.json')
];

For more info check: Fix CURL file uploads.

0
On

try $post = '@' .realpath('file_name.json')