Shihas
Shihas

Reputation: 814

Run curl inside php

I want to execute Curl code inside PHP.

curl -X POST 'https://api.sightengine.com/1.0/check.json' \
     -F 'api_user=1********5' \
     -F 'api_secret=q**************Q' \
     -F 'media=@/full/path/to/image.jpg' \
     -F 'models=nudity'   

Above code has four parameters to pass to the api. Below PHP code I tried to execute:

function image()
{
    $body_data = http_build_query(array('api_user' => 1********5,
                       'api_secret' => 'q**************Q',
                       'media' => $_FILES['image']['name'],
                       'models' => 'nudity'));

    // Configure cURL
    $image_curl = curl_init();
    curl_setopt($image_curl, CURLOPT_URL, "https://api.sightengine.com/1.0/check.json");
    curl_setopt($image_curl, CURLOPT_POST, true); // Use POST
    curl_setopt($image_curl, CURLOPT_POSTFIELDS, $body_data); // Setup post body
    curl_setopt($image_curl, CURLOPT_RETURNTRANSFER, true); // Receive server response

    // Execute request and read responce
    $session_response = curl_exec($image_curl);
    $response = json_decode($session_response);

    print_r($response);
}   

Response:

stdClass Object ( [status] => failure [request] => stdClass Object ( [id] => req_2365jHPuLcC6Bydh7WNd7 [timestamp] => 1512542730.57 [operations] => 0 ) [error] => stdClass Object ( [type] => argument_error [code] => 4 [message] => No media specified ) )

Now the problem is fro the media and models parameters.

  1. I'm not sure the file path to media parameter has some problem. And do I want to and an additional @ in-front of the path.

  2. I'm I defined all parameters in $body_data array and passing them to the CURLOPT_URL properly.

Please help me to solve this issue. When I try this in POSTMAN it works fine. Thanks in advance.

Upvotes: 0

Views: 2248

Answers (1)

Hari K T
Hari K T

Reputation: 4244

You don't need to use http_build_query.

PHP 5.5, 5.6 etc supported to pass @ sign, but deprecated in PHP 7. Now we can use https://secure.php.net/manual/en/class.curlfile.php .

$body_data = array(
    'api_user' => '3454',
    'api_secret' => 'q**************Q',
    'models' => 'nudity'
);

$body_data['media'] = new CurlFile(realpath('file.jpg'));

// Configure cURL
$image_curl = curl_init();
curl_setopt($image_curl, CURLOPT_URL, "https://api.sightengine.com/1.0/check.json");
curl_setopt($image_curl, CURLOPT_POST, true); // Use POST
curl_setopt($image_curl, CURLOPT_POSTFIELDS, $body_data); // Setup post body
curl_setopt($image_curl, CURLOPT_RETURNTRANSFER, true); // Receive server response

// Execute request and read responce
$session_response = curl_exec($image_curl);
$response = json_decode($session_response);

Upvotes: 1

Related Questions