Home >Backend Development >PHP Tutorial >How Can I Send POST Data to Web Pages Using cURL?

How Can I Send POST Data to Web Pages Using cURL?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 22:25:10647browse

How Can I Send POST Data to Web Pages Using cURL?

Passing POST Data to Pages using cURL

cURL is a powerful tool for making HTTP requests, allowing you to interact with web pages and services programmatically. One common task is passing POST data, which is used for submitting data to forms. Here's how to accomplish this with cURL:

Solution:

$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$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);

Explanation:

  • CURLOPT_POST enables HTTP POST.
  • CURLOPT_POSTFIELDS specifies the POST data as an array.

Data Encoding Options:

cURL provides two options for encoding POST data:

  • As an array: Data is sent as multipart/form-data, which may not be always accepted by the server.
  • As a URL-encoded string: Data is sent as application/x-www-form-urlencoded, as used in HTML form submissions.

To encode as a string, use http_build_query($data) as the value for CURLOPT_POSTFIELDS.

References:

  • [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 Send POST Data to Web Pages Using cURL?. 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