0

Situation

  • I want to post JSON data using php cURL into my url http://localhost/api_v2/url?key=***

Here is what I have tried

POST function

public function post(){

    $ch = curl_init("http://localhost/api_v2/url?key=***");

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $file_name = 'inventory.csv';
    $file_path = 'C:\\QuickBooks\\'.$file_name;
    $csv= file_get_contents($file_path);
    $utf8_csv = utf8_encode($csv);
    $array = array_map("str_getcsv", explode("\n", $utf8_csv));
    $json = json_encode($array, JSON_PRETTY_PRINT);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($json))                                                                       
    );

    curl_setopt( $ch, CURLOPT_POSTFIELDS, $json ); 

    curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));

    $result = curl_exec($ch);

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($status == 200){
        echo "Post Successfully!";
    }
}
8
  • 2
    I am not familiar with laravel, but don't you need to add line curl_setopt( $ch, CURLOPT_POSTFIELDS, $json ); before curl_exec($ch)? Commented Jan 30, 2015 at 19:07
  • agreed with Kim, strlen($json) is only to send the string length, but the post data has to be sent to the server in CURL Commented Jan 30, 2015 at 19:08
  • you should return something from your webservice controller Commented Jan 30, 2015 at 19:10
  • echo json_encode(['message'=>'Post Successfully!'']); exit() Commented Jan 30, 2015 at 19:20
  • 1
    @KimAlexander Please add your comment as an answer so the OP can accept it :) Commented Jan 30, 2015 at 19:29

2 Answers 2

5

Your error is in this line

curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));

Just change it to

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('json' => $json)));

Let me know, how it goes !

Sign up to request clarification or add additional context in comments.

Comments

3

I am not familiar with laravel,

but don't you need to add line

curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );

before

curl_exec($ch)?

3 Comments

When I used Postman test go to this url http://localhost/api_v2/url/post?key=*** I got Illuminate \ Session \ TokenMismatchException Do you know why ?
sorry, I have no idea what is your webservce is like... and what is Postman :-) ?
can you delete your answer, so I can delete this question Freely .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.