"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Send POST Data to a URL Using cURL in PHP?

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

Published on 2024-11-20
Browse:528

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3