Home >Backend Development >PHP Tutorial >How Can I Use cURL to Submit POST Data?

How Can I Use cURL to Submit POST Data?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 17:24:12611browse

How Can I Use cURL to Submit POST Data?

Post Data through cURL

Passing $_POST values to a different page can be achieved using cURL. The process involves activating HTTP POST and setting the post fields for cURL to handle.

Implementation:

$data = ['name' => 'Ross', 'php_master' => true];

// File upload support
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle);

Options:

  • CURLOPT_POST: Enables HTTP POST.
  • CURLOPT_POSTFIELDS: Specifies the post data.

Post Data Encoding:

cURL can encode data in two formats:

  1. Array: Posts as multipart/form-data (may not be supported by all servers).
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
  1. URL-encoded string: Posts as application/x-www-form-urlencoded (default encoding for HTML forms).
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));

Additional Resources:

  • [curl_init](https://www.php.net/manual/en/function.curl-init.php)
  • [curl_setopt](https://www.php.net/manual/en/function.curl-setopt.php)

The above is the detailed content of How Can I Use cURL to Submit POST Data?. 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