简体   繁体   中英

PHP using curl POST data in json - REST api not working

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.

// 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());
    }
});

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>';

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 = "mail@email.tld";


$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: mail@email.tld

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM