Php curl send json data

How to POST and Receive JSON Data using PHP cURL

JSON is the most popular data format for exchanging data between a browser and a server. The JSON data format is mostly used in web services to interchange data through API. When you working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. In this tutorial, we will show you how to POST JSON data using PHP cURL and get JSON data in PHP.

Send JSON data via POST with PHP cURL

The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.

  • Specify the URL ( $url ) where the JSON data to be sent.
  • Initiate new cURL resource using curl_init().
  • Setup data in PHP array and encode into a JSON string using json_encode().
  • Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.
  • Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
  • Return the response as a string instead of outputting it using the CURLOPT_RETURNTRANSFER option.
  • Finally, the curl_exec() function is used to execute the POST request.
// API URL $url = 'https://www.example.com/api'; 
// Create a new cURL resource $ch = curl_init($url);
// Setup request to send json via POST $data = array( 'username' => 'codexworld', 'password' => '123456' ); $payload = json_encode(array("user" => $data));
// Attach encoded JSON string to the POST fields curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Return response instead of outputting curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request $result = curl_exec($ch);
// Close cURL resource curl_close($ch);

Receive JSON POST Data using PHP

The following example shows how you can get or fetch the JSON POST data using PHP.

  • Use json_decode() function to decoded JSON data in PHP.
  • The file_get_contents() function is used to receive data in a more readable format.
$data = json_decode(file_get_contents('php://input'), true); 

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

How to Pass JSON Data in a URL using CURL in PHP ?

In this article, we will see how to pass the JSON Data in a URL using CURL in PHP, along with understanding the different ways for passing the data in a URL through the illustrations. The cURL stands for client URL, which allows us to connect with other URLs & use their responses in our code, i.e., it is a tool for sending and getting files using URL syntax. The cURL facilitates the way that can hit a URL from our code to get an HTML response from it. The cURL is also used in command lines or scripts for data transfer. Here, we need to pass JSON data in a URL using cURL in PHP and handle the POST request. This task can be accomplished with the help of the following ways:

We will explore all the above approaches & understand them through examples.

Syntax for passing JSON data in a URL using cURL:

Approach for POST Request:

  • We need to specify the URL, where the JSON data need to be sent.
  • Using curl_init(), we initialize cURL.
  • Put JSON data in a PHP array and set up JSON data.
  • And using json_encode() encode it into JSON string.
  • Setting the options for the cURL.
    • Fetching $url using CURLOPT_URL.
    • Switching request type from get to post using CURLOPT_POST.
    • Now attach the encoded string in the post field using CURLOPT_POSTFIELDS.
    • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
    • Using the CURLOPT_HTTPHEADER set the Content-Type to application/JSON.

    Example 1: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL POST Request.

    PHP

    Employee: Aman Job: Data Scientist Company: GeeksForGeeks id: 553 createdAt: 2022-12-02T12:32:42.420Z

    Approach for GET Request:

    • We need to specify the URL, Where the JSON data is going to be sent.
    • Using curl_init() we initialize cURL.
    • Next, we have to set options for the cURL.
    • Fetching $url using CURLOPT_URL.
    • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
    • Setting multiple options for a cURL session. Using the curl_setopt_array() function, setting a large number of options for cURL without repetitively calling it.
    • Using curl_exec() to execute the GET request.
    • Decode the response and Return the response as a string.
    • Close the cURL.

    Example 2: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL GET Request.

    PHP

    Array ( [page] => 2 [per_page] => 6 [total] => 12 [total_pages] => 2 [data] => Array ( [0] => Array ( [id] => 7 [email] => michael.lawson@reqres.in [first_name] => Michael [last_name] => Lawson [avatar] => https://reqres.in/img/faces/7-image.jpg ) [1] => Array ( [id] => 8 [email] => lindsay.ferguson@reqres.in [first_name] => Lindsay [last_name] => Ferguson [avatar] => https://reqres.in/img/faces/8-image.jpg ) [2] => Array ( [id] => 9 [email] => tobias.funke@reqres.in [first_name] => Tobias [last_name] => Funke [avatar] => https://reqres.in/img/faces/9-image.jpg ) [3] => Array ( [id] => 10 [email] => byron.fields@reqres.in [first_name] => Byron [last_name] => Fields [avatar] => https://reqres.in/img/faces/10-image.jpg ) [4] => Array ( [id] => 11 [email] => george.edwards@reqres.in [first_name] => George [last_name] => Edwards [avatar] => https://reqres.in/img/faces/11-image.jpg ) [5] =>Array ( [id] => 12 [email] => rachel.howell@reqres.in [first_name] => Rachel [last_name] => Howell [avatar] => https://reqres.in/img/faces/12-image.jpg ) ) [support] => Array ( [url] => https://reqres.in/#support-heading => To keep ReqRes free, contributions towards server costs are appreciated! ) )

    Approach for PUT Request:

    • We need to specify the URL, where the JSON data need to be sent.
    • Using curl_init(), we initialize cURL.
    • Put JSON data in a PHP array and set up JSON data.
    • And using json_encode() encode it into JSON string.
    • Setting the options for the cURL.
      • Fetching $url using CURLOPT_URL.
      • Now attach the encoded string in the post field using CURLOPT_POSTFIELDS.
      • Setting the curl option RETURNTRANSFER to true so that it returns the response instead of just outputting it.
      • Using the CURLOPT_HTTPHEADER set the Content-Type to application/JSON.

      Example 3: This example illustrates passing the JSON Data in a URL using cURL in PHP by using the cURL PUT Request.

      Источник

      How to Post JSON Data with PHP cURL & Receive It?

      Hi! Here let’s see how to post json data with php curl and receive the raw json sent. You can simply use PHP file_get_contents() to send HTTP GET request. But it’s not the same case with HTTP POST. Fortunately PHP cURL makes the process very simple. With curl you can easily send HTTP requests. In case you don’t know, ‘cURL’ is a library that let you communicate with web servers using different protocols such as http, https, ftp, telnet, file etc.

      To use curl, you must install libcurl package on your server according to the version of PHP you use.

      send http post json in php

      In case you are not sure if curl is enabled on your machine or not, use this code to check it.

      How to Post JSON with PHP cURL?

      In order to send HTTP POST request with JSON data, you have to follow some steps and they are,

      1. Format JSON data correctly
      2. Attach JSON to the body of the POST request
      3. Set the right content type with HTTP headers
      4. Send the request.

      The following is the PHP code to send json through POST request.

       'mydomain.com', 'account' => 'admin', 'status' => 'true' ); $json = json_encode($data); // send post request $ch = curl_init($url); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); echo $result; ?>

      Here is the explanation for the functions & curl options we have used in the above script:

      • curl_init() — Initialize a curl session, takes up a parameter URL to send post request.
      • curl_setopt() — Set the curl options.
      • CURLOPT_POSTFIELDS — This option will set the data to the body of the http request.
      • CURLOPT_HTTPHEADER — Option to set http headers. It is important to define the right content type here, so that the remote server understands what we sent. To send json, the content type should be set to ‘application/json’.
      • CURLOPT_RETURNTRANSFER — Setting this to TRUE will place the response from the remote server on $result variable instead of outputting it.
      • curl_exec() — Send the HTTP request.
      • curl_close() — Close the curl session.

      Retrieve the Posted JSON:

      Okay! We have sent json data via http post request. But what will happen at the receiving end? How should we retrieve the incoming json?

      Well! In our example we have sent raw json data. This can be accessed through php’s input stream. Below is the code to receive the json posted,

      You can decode the json and process it as you want. Pretty simple!

      That explains about posting json data and receiving it using PHP cURL. This is not very different from sending a regular POST request. However, we are doing it over HTTP here. Hopefully, this tutorial is useful for you. Please don’t forget to share it with your friends.

      Источник

      How to Post JSON Data using cURL in PHP

      How to Post JSON Data using cURL in PHP

      JSON is the most popular data format on the web because it is natively supported in JavaScript and human-readable.

      As such, many APIs support the ability to send and receive JSON data.

      In this tutorial, we will learn how to send JSON data to a URL using cURL in PHP.

      Sending JSON Data to a URL

      To send JSON data to a URL, first let’s define the array we want to send:

      Now let’s encode the array as JSON:

      Not that we have our JSON, let’s initialize a cURL request:

      Now let’s apply a few options:

      Finally, let’s execute the request:

      Now, we can close the cURL request:

      Taken all together, we can write a reusable function for this:
       'John Doe', 'age' => 30 ]; function post_json($url, $data) < $json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]); $output = curl_exec($ch); curl_close($ch); return $output; >$output = post_json('https://example.com/api', $data); echo $output; 

      Conclusion

      In this post, we learned how to send JSON data to a URL using cURL in PHP.

      Simply initialize a new cURL request, apply a few options, and execute the request with the given url and data.

      Then, we can close the cURL request and return the output.

      If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

      Give feedback on this page , tweet at us, or join our Discord !

      Источник

      Читайте также:  Ispmanager изменить версию php apache
Оцените статью