How to Pass JSON Data in a URL using CURL in PHP ? - GeeksforGeeks (2024)

Last Updated : 29 Mar, 2023

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

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:

  • cURL POST Request
  • cURL GET Request
  • cURL PUT Request

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

Syntax for passing JSON data in a URL using cURL:

<?php $url = "https://reqres.in/api/users"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); $resp = curl_exec($ch); curl_close($ch);?>
  • By using the cURL POST Request

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.
  • 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 POST request.
  • Decode the response and Return the response as a string.
  • Close the cURL.

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

PHP

<?php

//URL, Where the JSON data is going to be sent

// sending post request to reqres.in

//initialize CURL

$ch = curl_init();

//setup json data and using json_encode() encode it into JSON string

$data = array(

'Employee' => 'Aman',

'Job' => 'Data Scientist',

'Company' => '<b>GeeksForGeeks</b>'

);

$new_data = json_encode($data);

//options for curl

$array_options = array(

//set the url option

CURLOPT_URL=>$url,

//switches the request type from get to post

CURLOPT_POST=>true,

//attach the encoded string in the post field using CURLOPT_POSTFIELDS

CURLOPT_POSTFIELDS=>$new_data,

//setting curl option RETURNTRANSFER to true

//so that it returns the response

//instead of outputting it

CURLOPT_RETURNTRANSFER=>true,

//Using the CURLOPT_HTTPHEADER set the Content-Type to application/json

CURLOPT_HTTPHEADER=>array('Content-Type:application/json')

);

//setting multiple options using curl_setopt_array

curl_setopt_array($ch,$array_options);

// using curl_exec() is used to execute the POST request

$resp = curl_exec($ch);

//decode the response

$final_decoded_data = json_decode($resp);

foreach($final_decoded_data as $key => $val){

echo $key . ': ' . $val . '<br>';

}

//close the cURL and load the page

curl_close($ch);

?>

Output:

Employee: AmanJob: Data ScientistCompany: GeeksForGeeksid: 553createdAt: 2022-12-02T12:32:42.420Z
  • By using cURL GET Request

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

<?php

//URL, Where the JSON data is going to be sent

// sending get request to reqres.in

//initialize CURL

$ch = curl_init();

//next we have to set options so below is the options for the curl

$array_options = array(

// $url is the variable we want to fetch using CURLOPT_URL

CURLOPT_URL=>$url,

//setting curl option RETURNTRANSFER to true so

//that it returns the response

//instead of outputting it

CURLOPT_RETURNTRANSFER=>true,

);

//setting multiple options using curl_setopt_array

curl_setopt_array($ch,$array_options);

// using curl_exec() is used to execute the POST request

$resp = curl_exec($ch);

// decode the response

$final_decoded_data = json_decode($resp,true);

print_r($final_decoded_data);

//close the cURL and load the page

curl_close($ch);

?>

Output:

Array ( [page] => 2 [per_page] => 6 [total] => 12 [total_pages] => 2 [data] => Array ( [0] => Array ( [id] => 7 [email] => [email protected] [first_name] => Michael [last_name] => Lawson [avatar] => https://reqres.in/img/faces/7-image.jpg ) [1] => Array ( [id] => 8 [email] => [email protected] [first_name] => Lindsay [last_name] => Ferguson [avatar] => https://reqres.in/img/faces/8-image.jpg ) [2] => Array ( [id] => 9 [email] => [email protected] [first_name] => Tobias [last_name] => Funke [avatar] => https://reqres.in/img/faces/9-image.jpg ) [3] => Array ( [id] => 10 [email] => [email protected] [first_name] => Byron [last_name] => Fields [avatar] => https://reqres.in/img/faces/10-image.jpg ) [4] => Array ( [id] => 11 [email] => [email protected] [first_name] => George [last_name] => Edwards [avatar] => https://reqres.in/img/faces/11-image.jpg ) [5] =>Array ( [id] => 12 [email] => [email protected] [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! ) )
  • By using cURL PUT Request

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.
  • Instead of using CURLOPT_POST, we use here CURLOPT_CUSTOMREQUEST for specifying the PUT request.
  • 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 PUT request.
  • Decode the response and Return the response as a string.
  • Close the curl.

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

PHP

<?php

//URL, Where the JSON data is going to be sent

// sending put request to reqres.in

//initialize CURL

$ch = curl_init();

//setup json data and using json_encode() encode it into JSON string

$data = array(

'Employee' => 'Aman',

'Job' => 'Data Scientist',

'Company' => '<b>GeeksForGeeks</b>'

);

$new_data = json_encode($data);

//next we have to set options so below is the options for the curl

$array_options = array(

//set the url option

CURLOPT_URL=>$url,

//attach the encoded string in the post field using CURLOPT_POSTFIELDS

CURLOPT_POSTFIELDS=>$new_data,

//setting curl option RETURNTRANSFER to true so

//that it returns the response

//instead of outputting it

CURLOPT_RETURNTRANSFER=>true,

//Using the CURLOPT_HTTPHEADER set the Content-Type to application/json

CURLOPT_HTTPHEADER=>array('Content-Type:application/json')

);

//curl option for switching the request type from get to post

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'PUT');

//setting multiple options using curl_setopt_array

curl_setopt_array($ch,$array_options);

// using curl_exec() is used to execute the POST request

$resp = curl_exec($ch);

// decode the response

$decoded = json_decode($resp);

foreach($decoded as $key => $val){

echo $key . ': ' . $val . '<br>';

}

//close the cURL and load the page

curl_close($ch);

?>

Output:

Employee: AmanJob: Data ScientistCompany: GeeksForGeeksupdatedAt: 2022-12-02T12:34:59.262Z


dixitaditya2001

How to Pass JSON Data in a URL using CURL in PHP ? - GeeksforGeeks (3)

Improve

Next Article

How to Post JSON Data using Curl ?

Please Login to comment...

Similar Reads

How to use cURL to Get JSON Data and Decode JSON Data in PHP ? In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website, 2 min read How to Post JSON Data using Curl ? One can send the post data using curl (Client for URLs), a command line tool, and a library for transferring data with URLs. It supports various types of protocols. Most of the use cases of the curl command are posting JSON data to a server endpoint. CURLcURL stands for ( Client for URLs) and is a command line tool and library for transferring data 3 min read Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json? In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config 6 min read How to pass multiple JSON Objects as data using jQuery's $.ajax() ? The purpose of this article is to pass multiple JSON objects as data using the jQuery $ajax() method in an HTML document. Approach: Create a button in an HTML document to send JSON objects to a PHP server. In the JavaScript file, add a click event listener to the button. On clicking of the button, a request is made to PHP file using jQuery $ajax() 3 min read How to get Geolocation using PHP-cURL from IP Address ? Geolocation refers to the identification of the geographical location of a user or computer device. In this article, we will create a web page where the user can enter the IP Address of any device, and then the server will provide Geolocation of the IP address fetching the following details using the IP Geolocation API. Continent NameCountry NameCo 2 min read Web Scraping using cURL in PHP We all have tried getting data from a website in many ways. In this article, we will learn how to web scrape using bots to extract content and data from a website. We will use PHP cURL to scrape a web page, it looks like a typo from leaving caps lock on, but that’s really how you write it. cURL is the system used to make HTTP requests with PHP. It 2 min read How to make a request using HTTP basic authentication with PHP curl? Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user credentials securely but also ensuring that the PHP 3 min read Pass by Value and Pass by Reference in Javascript JavaScript, being a versatile and dynamic programming language, employs different strategies for passing variables to functions. Two common approaches are "pass by value" and "pass by reference". Understanding these concepts is important for writing efficient and bug-free code. Pass By ValueWhen a function is called, the value of the variable is di 4 min read How to get cookies from curl into a variable in PHP ? The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certification), etc. This example will illustrate how to get cookies from a PHP cURL into a variable. The functions provide an option to set a callback that will be called for each response he 2 min read How to enable cURL in PHP? Often, web applications require HTTP based UserID and Password authentication, cookies, and form uploads. Even, user authentication with Google or Facebook sign-in is done via HTTP. In these types of cases, we need to request a particular service server(Like Google's) for user validation and authentication token on our server. The entire process ta 3 min read Why use Guzzle Instead of cURL in PHP ? What is cURL? cURL is a module in PHP with we can use libcurl. The libcurl is a library that is used in PHP to create connection and communicate with various kinds of different servers which may have different type of protocols. cURl provide us various pre-built functions like - curl_init(), curl_setopt(), curl_exec(), curl_close().Limitations of c 2 min read How to install the ext-curl extension with PHP 7 ? The ext-curl CURL stands for client user, In Linux cURL is a PHP extension, that allows us to receive and send information via the URL syntax. And ext-curl is the extension in the latest PHP-7 which is loaded with some of the advanced features of the basic curls. The following are the steps to add ext-curl extension in Ubuntu - 1. Update the Extens 1 min read PHP | cURL The cURL stands for 'Client for URLs', originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as 'see URL'. The cURL project has two products libcurl and curl. libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcu 3 min read Convert relative path URL to absolute path URL using JavaScript Given a relative URL, the task is to convert the relative URL to an absolute URL. Here, the base URL is also given. 2 approaches are discussed here, the first example has the baseURL provided by the user and the second takes it from the URL of the page. Approach 1: Get the relURL and baseURL from user.Use .split() method to split the base and relat 3 min read Sending HTTP Request Using cURL Set-1 Whenever we are dealing with HTTP requests, cURL simplifies our tasks to a great extent and is the easiest tool to get our hands dirty on. cURL: It stands for "client URL" and is used in command line or scripts to transfer data. It is a great tool for dealing with HTTP requests like GET, POST, PUT, DELETE, etc. Although it provides us with the supp 3 min read How to POST a XML file using cURL? This article explains how to use the cURL command-line tool to send an XML file to a server using a POST request. A POST request is commonly used to submit data to a server. There are two main approaches to include the XML data in your cURL request: Table of Content Reading from a FileProviding Inline DataReading from a FileThis is the most common 2 min read How to Pass JSON Values into React Components ? In React, you can pass JSON values into components using props. Props allow us to send data from a parent component to its child components. When rendering a component, you can pass the JSON values as props. These props can then be accessed within the component’s function or class, allowing you to display the desired data. Table of Content Passing 3 min read How to Import cURL Request into Postman ? Postman is an API development tool that helps us do everything related to APIs, make API calls, perform API testing, create automations, etc. This is a one-step tool to perform operations on the backend server, and show the outputs in various readable formats. In this article, we will learn how to import a cURL request into postman. Creating a cURL 2 min read How to Convert a Postman Request to cURL? If you're a web developer, quality assurance engineer, or system administrator, chances are you're familiar with Postman, a crucial tool for API testing. However, there are instances where you may need to convert a Postman request to cURL, a command-line tool for data transfer. This article provides a simple step-by-step guide on how to perform thi 3 min read How to parse JSON object using JSON.stringify() in JavaScript ? In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete 2 min read How to transforms JSON object to pretty-printed JSON using Angular Pipe ? JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p 3 min read How to Convert XML data into JSON using PHP ? In this article, we are going to see how to convert XML data into JSON format using PHP. Requirements: XAMPP Server Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data. Structure of XML: 3 min read How to Insert JSON data into MySQL database using PHP? To insert JSON data into MySQL database using PHP, use the json_decode function in PHP to convert JSON object into an array that can be inserted into the database. Here, we are going to see how to insert JSON data into MySQL database using PHP through the XAMPP server in a step-by-step way. JSON Structure:[{ "data1": "value1", "data2": "value2", . 3 min read JSON Modify an Array Value of a JSON Object The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi 2 min read What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ? JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip 2 min read How to Write Postman Test to Compare the Response JSON against another JSON? In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh 4 min read Convert JSON String to Array of JSON Objects in JavaScript Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solving this problem, which are discussed below: Table of Content Using JSON.parse() MethodUsing JavaScript eval() MethodUsing Function ConstructorU 4 min read Difference between package.json and package-lock.json files In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content 4 min read How to access data sent through URL with GET method in PHP ? On a website, we often use forms to collect data, login/signup boxes for users, a search box to search through a web page, etc. So input fields are used to make the website interactive and to collect data. But we know that HTML can not store the data in a database so for that we use a backend scripting language like PHP. URLs structure for GET meth 2 min read

Article Tags :

  • PHP
  • Technical Scripter
  • Web Technologies
  • PHP-cURL
How to Pass JSON Data in a URL using CURL in PHP ? - GeeksforGeeks (2024)
Top Articles
Akshat Shrivastava on LinkedIn: If you make 1 Lakh, live with 50,000, especially when you are young. My… | 351 comments
Why Graphic Design using Canva is important?
Oldgamesshelf
Craigslist Houses For Rent In Denver Colorado
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
877-668-5260 | 18776685260 - Robocaller Warning!
Women's Beauty Parlour Near Me
Tlc Africa Deaths 2021
Baseball-Reference Com
Best Pawn Shops Near Me
W303 Tarkov
Brutál jó vegán torta! – Kókusz-málna-csoki trió
454 Cu In Liters
George The Animal Steele Gif
Define Percosivism
How Much Is Tay Ks Bail
Pickswise Review 2024: Is Pickswise a Trusted Tipster?
A Biomass Pyramid Of An Ecosystem Is Shown.Tertiary ConsumersSecondary ConsumersPrimary ConsumersProducersWhich
Amortization Calculator
Craigs List Tallahassee
Red Cedar Farms Goldendoodle
Xfinity Cup Race Today
UMvC3 OTT: Welcome to 2013!
Sofia the baddie dog
The Boogeyman (Film, 2023) - MovieMeter.nl
Guinness World Record For Longest Imessage
Helpers Needed At Once Bug Fables
Kempsville Recreation Center Pool Schedule
Best New England Boarding Schools
Ripsi Terzian Instagram
Nacogdoches, Texas: Step Back in Time in Texas' Oldest Town
How to Draw a Bubble Letter M in 5 Easy Steps
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Sitting Human Silhouette Demonologist
KM to M (Kilometer to Meter) Converter, 1 km is 1000 m
Deshuesadero El Pulpo
Miracle Shoes Ff6
Suffix With Pent Crossword Clue
Andrew Lee Torres
Jetblue 1919
Mudfin Village Wow
Foxxequeen
705 Us 74 Bus Rockingham Nc
Kate Spade Outlet Altoona
Hughie Francis Foley – Marinermath
Myapps Tesla Ultipro Sign In
O'reilly's On Marbach
Noelleleyva Leaks
Rise Meadville Reviews
Marion City Wide Garage Sale 2023
Southwind Village, Southend Village, Southwood Village, Supervision Of Alcohol Sales In Church And Village Halls
O'reilly's Eastman Georgia
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 5545

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.