Home Backend Development PHP Tutorial How to send a POST request containing JSON data using PHP's cURL library?

How to send a POST request containing JSON data using PHP's cURL library?

Apr 01, 2025 pm 03:12 PM
tool red

How to send a POST request containing JSON data using PHP's cURL library?

This article will demonstrate how to use PHP's cURL library to send POST requests containing JSON data and interact with external APIs. Suppose you need to send JSON data containing appid , secret and an fields to the target server.

Solution:

Use the curl_setopt_array function to set the cURL option to realize the POST request to send JSON data. The following code snippet shows the specific implementation:

 <?php $curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'http://localhost/xxx', // Replace with your target URL
  CURLOPT_RETURNTRANSFER => true, // Return the result as the string CURLOPT_ENCODING => '', // Allow any encoding CURLOPT_MAXREDIRS => 10, // Maximum redirection CURLOPT_TIMEOUT => 0, // Timeout, 0 means infinite CURLOPT_FOLLOWLOCATION => true, // Allow redirection CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // HTTP version CURLOPT_CUSTOMREQUEST => 'POST', // The request method is POST
  CURLOPT_POSTFIELDS => json_encode([ // Use json_encode function to encode JSON data "appid" => "111",
    "secret" => "ddd111",
    "an" => "xxx"
  ]),
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json', // Specify the content type as JSON
    'Cookie: lang=zh-cn; ssid=02bebb340032d3a9e4b15463dd7d0eaa' // Optional Cookie
  ],
]);

$response = curl_exec($curl); // Execute the request curl_close($curl); // Close the cURL resource echo $response; // Output the response result?>

Code description:

  • CURLOPT_POSTFIELDS uses the json_encode function to encode the PHP array into a JSON string to ensure the correct format of the data.
  • CURLOPT_HTTPHEADER sets Content-Type to application/json and tells the server that the request body is JSON format. Please replace the target URL, JSON data and cookie information according to the actual situation.

In order to more conveniently debug and generate cURL request codes in different languages, it is recommended to use tools such as Postman. Postman can generate code snippets in multiple languages, including PHP's cURL code, which facilitates developers to quickly build and test requests.

With Postman or similar tools, you can more effectively understand the meaning of parameters and set methods, so that API interactions are more efficient.

The above is the detailed content of How to send a POST request containing JSON data using PHP's cURL library?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a stablecoin? How does it work? A list of the most well-known stablecoins What is a stablecoin? How does it work? A list of the most well-known stablecoins Sep 24, 2025 pm 01:54 PM

Directory What is a stablecoin? How does stablecoins work? The decentralized support of cryptocurrencies is based on traditional assets. The classification of stablecoins is supported by algorithms. The stablecoin with fiat currency collateral assets B. The stablecoin with cryptocurrency collateral assets C. Why does the algorithmic stablecoin have stablecoins? The most well-known stablecoins at a glance. Tether (USDT) BinanceUSD (BUSD) USDCoin (USDC) DAI (DAI) Stablecoins Pros and Cons. Stablecoins Controversy and Future Controversy Points: Future Trends: Conclusion: Stablecoins and their role in the cryptocurrency world. What are the common questions about stablecoins? What is the best stablecoin?

What is MemeCoin? How does it work? The most famous meme coins What is MemeCoin? How does it work? The most famous meme coins Sep 24, 2025 pm 01:48 PM

Table of Contents Definition: What is a meme coin? Why do meme coins exist? What's special about meme coins? How does meme coins work? The most well-known meme coins overview Dogecoin (DOGE), Shiba Inu (SHIB), Pepe (PEPE), Bonk (BONK) FLOKI (FLOKI) Meme Coin (MEME) Meme Coin Opportunities and Risks How to Buy Meme Coins? Conclusion: The future of meme coins in the crypto world What are the common questions about meme coins? What is the best meme coin? What is the prediction of meme coins? What should you consider when purchasing meme coins? What role does market capitalization play in meme coins? Meme coins are usually popular on the Internet

What is BIP? Why are they so important to the future of Bitcoin? What is BIP? Why are they so important to the future of Bitcoin? Sep 24, 2025 pm 01:51 PM

Table of Contents What is Bitcoin Improvement Proposal (BIP)? Why is BIP so important? How does the historical BIP process work for Bitcoin Improvement Proposal (BIP)? What is a BIP type signal and how does a miner send it? Taproot and Cons of Quick Trial of BIP Conclusion‍Any improvements to Bitcoin have been made since 2011 through a system called Bitcoin Improvement Proposal or “BIP.” Bitcoin Improvement Proposal (BIP) provides guidelines for how Bitcoin can develop in general, there are three possible types of BIP, two of which are related to the technological changes in Bitcoin each BIP starts with informal discussions among Bitcoin developers who can gather anywhere, including Twi

This computer can't be stuck when resetting win10_Solve the problem that the system progress of Win10 resetting is stuck at a certain percentage This computer can't be stuck when resetting win10_Solve the problem that the system progress of Win10 resetting is stuck at a certain percentage Sep 24, 2025 pm 05:30 PM

When the reset computer is stuck, wait and observe the activity of the hard disk to confirm whether it is running; then disconnect the network to avoid update interference, or enter safe mode to eliminate software conflicts; check disk errors through chkdsk, clean the SoftwareDistribution cache to fix update problems; if it is still invalid, use Windows installation media to start the repair and perform the reset operation.

How to clean the C drive of Win10 system when it is full_Win10 system C drive space cleaning method How to clean the C drive of Win10 system when it is full_Win10 system C drive space cleaning method Sep 24, 2025 pm 05:36 PM

First, use the disk cleaning tool to delete temporary files and old version updates, then manually clear the cache in the %temp% and C:\Windows\Temp directory. Then execute powercfg-hoff to close hibernation and release hiberfil.sys space through the administrator command prompt, and then migrate the virtual memory paging file to other disks. Finally, by compressing adjacent partitions and expanding the capacity of the C disk or using third-party tools to complete the capacity expansion operation.

This article explains that the Ethereum (ETH) unblocking queue shows a 'parabolic' trend: What does this mean for prices? This article explains that the Ethereum (ETH) unblocking queue shows a 'parabolic' trend: What does this mean for prices? Sep 24, 2025 pm 12:51 PM

Key points of the catalog: Ethereum unblocking queue hits a record $12 billion ETH. Strong institutional demand alleviates ETF sell-off concerns. Amid the nearly 100% rise in Ethereum prices over the past year, a considerable portion of the nearly $12 billion ETH currently waiting to be withdrawn may be used to make profits. Key points: The amount of Ethereum unstaking queuing has reached a record $12 billion, and it is currently 44 days to wait for the unstaking. Since July 1, the total holdings of strategic reserves and spot ETHETFs have increased by 116%, effectively hedging the market's concerns about large-scale selling. The scale of de-staking queues on the Ethereum network has climbed to its historical peak, indicating that investors may be working to realize the huge gains this year. Ethereum unblocked queue hits $12 billion E

What to do if the SD card cannot be read by the win10 computer_Solutions for the win10 system to not recognize the SD card What to do if the SD card cannot be read by the win10 computer_Solutions for the win10 system to not recognize the SD card Sep 24, 2025 pm 05:27 PM

First check the physical connection and lock switch of the SD card to ensure that it is inserted correctly and is not locked; then enable or restart the card reader device in the Device Manager; then update or reinstall the driver; run sfc/scannow to repair the system files; finally assign a disk letter or online to the SD card through disk management.

What is Portals (PORTALS) currency? What is the future potential? Price forecast for 2025-2030 What is Portals (PORTALS) currency? What is the future potential? Price forecast for 2025-2030 Sep 24, 2025 pm 01:27 PM

Table of Contents 1. What is the Portals project? 2. PORTALS Token Economic Model Token Details Token Allocation Token Utility Initial Circulation 3. The Latest Price Trends and Market Analysis of PORTALS Tokens 4. PORTALS Token Price Forecast 5. Risks and Opportunities of Investing in PORTALS Tokens Main Risks 6. Conclusion: How to View the Future of Portals? Amid the wave of the crypto world, the Portals project has attracted a lot of attention with its unique concepts and technologies. If your curiosity about Portals is surging, wondering about the future value of the PORTALS tokens

See all articles