Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-11-19 03:59:03244browse

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!

Statement:
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