1
function processCurlJsonrequest($URL, $fieldString)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
    curl_setopt($ch, CURLOPT_URL, $URL);
    // curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    // curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file_path);
    //curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file_path);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fieldString));
    curl_setopt($ch, CURLOPT_POST, 1);
    $resulta = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
    }
    return $resulta;
}
$data_string = array("title" => "jdsdfds","url"=>"sdfdfd","date"=>"2014-01-30");
processCurlJsonrequest('http://localhost/articles',$data_string);

Hi, I am using REST api post method, type JSON to post data by using curl function. But its not working at all and no output is showing.

I did test this by using Fiefox plugin RESTClient. its works fine, able to post data into my database. I am stuck when using PHP curl method to post data. Above is one of the example i took from internet but still not working. Need advice from senior.

5
  • Hi, you could possibly do this without using the POST method, as you can send a request to the server as a GET, just url_encode the query then url_decode it at the endpoint from client ? Commented Sep 8, 2015 at 20:57
  • Hi, the thing is i need to post data not to get data.correct me if i get you wrong Commented Sep 8, 2015 at 21:04
  • Hi, its possible to send data with the $_GET['']; parameters as well :), i for example use it do create an user on a remote DB Commented Sep 8, 2015 at 21:12
  • is the url http or https? Commented Sep 8, 2015 at 21:13
  • its http -> localhost/articles. sorry i dont get you. Commented Sep 8, 2015 at 21:16

5 Answers 5

1
// Handle POST requests to /articles
$app->post('/articles', function () use ($app) {
    try {
        // get and decode JSON request body
        $request = $app->request();
        $body = $request->getBody();
        $input = json_decode($body);

        $count = count($input);

        for ($x = 0; $x < $count; $x++) {

            // store article record
            $article = R::dispense('articles');
            $article->title = (string)$input[$x]->title;
            $article->url = (string)$input[$x]->url;
            $article->date = (string)$input[$x]->date;
            $id = R::store($article);

            // return JSON-encoded response body
            $app->response()->header('Content-Type', 'application/json');
            echo json_encode(R::exportAll($article));
        }
    } catch (Exception $e) {
        $app->response()->status(400);
        $app->response()->header('X-Status-Reason', $e->getMessage());
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

the error is line 142 is - >$article->title = (string)$input[$x]->title;
Add some debugging code, like var_dump(json_decode($body)); to figure out whats wrong with the data. Sometimes its better to work with an array (second parm of json_decode), so var_dump(json_decode($body, true)); and $input = json_decode($body, true); + $article->title = $input[$x]['title'];.
Hi Jens, var_dump saved my life. its able to retrieve the data when var dump. Then i realise its not in array format. so i did change by adding Array to this $input = array(json_decode($body,true));. now my code is working and data able to save into my db.
Unfortunately i had another problem. if i has array list like this : $data_string = array("title" => "test12345,test12345","url"=>"htttp,http2","date"=>"2014-01-30,2014-01-31"); The data inserting only the first array position not the second as well.
0

this is something ive used if you already know every parameter that is going to be added.

client.php:

<?php
$Username = "TestUsername";
$Password = "Password123";
$Email = "[email protected]";


$Url = "http://localhost/your/path/server.php?Username=$Username&Password=$Password&Email=$Email";


//send request:
$Client = curl_init($Url);


curl_setopt($Client, CURLOPT_RETURNTRANSFER, 1);


//response:
$Response = curl_exec($Client);


//decode:
$Result = json_decode($Response);

if($Result->Status==200){

$Output .= "Success, $Result->StatusMessage ($Result->Status)<br/> Data:<br/>";
$Output .= "Username: " . $Result->Information->Username . "<br/>";
$Output .= "Password: " . $Result->Information->Password . "<br/>";
$Output .= "Email: " . $Result->Information->Email . "<br/>";

echo $Output;



}
else{
echo "an error occured.";
}

Server.php:

<?php
header("Content-Type:application/json");


$Username = $_GET['Username'];
$Password = $_GET['Password'];
$Email = $_GET['Email'];

$HTTPSTATUS = 200;
$HTTP_MESSAGE = "RECORD ADDED.";


$Info = array(
'Username' => $Username,
'Password' => $Password,
'Email' => $Email
);

header("HTTP/1.1 $HTTPSTATUS $HTTP_MESSAGE");


$Response['Status'] = $HTTPSTATUS;
$Response['StatusMessage'] = $HTTP_MESSAGE;
$Response['Information'] = $Info;


$Return = json_encode($Response);

echo $Return;

This would be the result:

   Success, RECORD ADDED. (200)data:
    Username: TestUsername
    Password: Password123
    Email: [email protected]

Now, im no expert at this, but this works like a charm for me.

1 Comment

HI Kris, thanks for your reply. Now i noticed that its actually error coming from my api request got error. please see my post.
0

I know that, from the example above, the url is a standard http request yet the code references ssl. Also, you set the RETURNTRANSFER yet do not echo / print the result - only printing the error if there is one. I have found that it is essential to have a copy of cacert.pem - download from here ~ edit the path according to your server config. If the site is not https then it gets ignored anyway.

 function processCurlJsonrequest($URL, $fieldString) {

    $cacert=realpath( 'c:/wwwroot/cacert.pem' );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if( parse_url( $URL,PHP_URL_SCHEME )=='https' ){
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
        curl_setopt( $ch, CURLOPT_CAINFO, $cacert );
    }
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fieldString ) );
    curl_setopt($ch, CURLOPT_POST, true); 
    $results=curl_exec($ch);
    $errors=curl_error($ch);
    curl_close($ch);

    return array(
        'results'=>$results,
        'errors'=>$errors
    );
}

Notices that the function returns an array, you would need to account for that when dealing with the response....

$data_string = array("title" => "jdsdfds","url"=>"sdfdfd","date"=>"2014-01-30");
$response = processCurlJsonrequest('http://localhost/articles',$data_string);

echo '<pre>',print_r($response,true),'</pre>';

9 Comments

Hi RamRider, i received this error. Array ( [results] => Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\phpstorm_workspace\slim\index.php on line 142 [errors] => )
This error refers, I presume, to the code you recently posted above rather than the editing curl request function? I think what you need to do in your code above is include "true" in the json_decode call, viz: json_decode($body,true) ~ that will convert to an array rather than a json object
i did that -json_decode($body,true) and the errors is gone. but still no luck. data not save into db and no output has display Array ( [results] => [errors] => )
is there anything printed to screen? I would suggest using some debug statements in the function that handles the POST request to see what is happening.Does the db get updated?
the output shows : Array ( [results] => [errors] => ) . its empty Nop.its not updating in DB
|
0

I did change code a bit from :

// store article record
 $article = R::dispense('articles');
 $article->title = (string)$input[$x]->title;
 $article->url = (string)$input[$x]->url;
 $article->date = (string)$input[$x]->date;
 $id = R::store($article);

to this :

   // store article record
         $article = R::dispense('articles');
         $article->title = $input[$x]['title'];
         $article->url   = $input[$x]['url'];
         $article->date  = $input[$x]['date'];
         $id = R::store($article);

Now I'm able to post from Firefox rest-client plugin. able to post and create data in db. But still its not working when I tried from the PHP curl code.

1 Comment

RamRider, i did removed the content type but still no luck.
0

You should try this

$url = 'Your url';  
$args = 'Your argumnts';

  $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($args));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        $result = curl_exec($ch);
        curl_close($ch);
      return $result ? json_decode($result, true) : false;

Comments

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.