2

I have created an API in PHP to save the form data in the database. The API will be used for both Web and Mobile APP. The API is receiving data in JSON an sends the response in JSON only. I am using PHP CURL to call the API, no AJAX call will be there.

API (employee-registration.php)

<?php
    $params = file_get_contents('php://input');     // Input stream

    // Set initial values
    $salutation = $first_name = $last_name = $email = "";

    // Extract data
    $json = json_decode($params);

    $salutation         = trim($json->salutation);
    $first_name         = trim($json->first_name);
    $last_name          = trim($json->last_name);
    $email              = trim($json->email);

    // Do the validation and save data in database
    // Then send response in JSON

    $obj = new stdClass();
    $obj->status = $status;
    $obj->message = $message;
    $obj->errors = $errors;
    echo json_encode($obj);
?>

Call API using CURL

<?php
    $site_path = "http://www.mywebsite.com/";

    $postData = array(
        'salutation'    => 'mr',
        'first_name' => 'John',
        'last_name' => 'Pinto',
        'email' => 'test@website.com'
    );
    $postData = json_encode($postData);
    $ch = curl_init();  
    $url = $site_path.'path/to/api/employee-registration.php';
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, count($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    $output=curl_exec($ch);
    curl_close($ch);

    echo $output;
?>

The above things are working perfect, I am sending JSON data to the API and receiving JSON data from the API. But what if there is a file with all other data, say profile_picture. How can I modify the API so that it can receive data in JSON from Web and Mobile APP with the file? Ajax call is not allowed here, I have to use CURL for Web. please help

Shan Biswas
  • 79
  • 1
  • 1
  • 9
  • Not exactly a duplicate but here's how you send the data ~ https://stackoverflow.com/q/9081079/283366. As for how to receive / decode the request, you may just need to experiment. I'm not entirely sure what data will be in the `php://input` stream for a `multipart/form-data` request – Phil May 23 '18 at 04:32
  • Thank you for your comment but that did not solve my problem – Shan Biswas May 23 '18 at 15:29

0 Answers0