Home > Backend Development > PHP Tutorial > How to Send POST Data to a URL Using cURL in PHP?

How to Send POST Data to a URL Using cURL in PHP?

DDD
Release: 2024-11-19 03:59:03
Original
284 people have browsed it

How to Send POST Data to a URL Using cURL in PHP?

Sending POST Data to a URL in PHP

When you need to send POST data to a URL without relying on an HTML form, PHP's cURL extension provides a powerful solution. Here's how to accomplish it:

Using cURL:

  1. Initialize a cURL session with curl_init( $url ). Replace $url with the target URL.
  2. Set CURLOPT_POST to 1 to enable POST data sending.
  3. Prepare your POST data in a string, using & to separate key-value pairs. For example: $myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2.
  4. Assign the POST data to CURLOPT_POSTFIELDS using curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars ).
  5. Enable following redirects with curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ).
  6. Disable header output with curl_setopt( $ch, CURLOPT_HEADER, 0 ).
  7. Set CURLOPT_RETURNTRANSFER to 1 to retrieve the response as a string.
  8. Execute the cURL session with curl_exec( $ch ).
  9. Store the response in a variable, such as $response.

This approach allows you to send POST data directly from PHP code, enabling you to automate form submissions or transfer data without using an HTML form.

The above is the detailed content of How to Send POST Data to a URL Using cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template