Home > Backend Development > PHP Tutorial > How to Pass POST Values Using cURL in PHP?

How to Pass POST Values Using cURL in PHP?

Mary-Kate Olsen
Release: 2024-12-06 07:51:10
Original
197 people have browsed it

How to Pass POST Values Using cURL in PHP?

Passing POST Values with cURL

To pass POST values using cURL, you can follow these steps:

Step 1: Create an Array of POST Data

Group the data you want to submit in an array, where the keys represent form field names and the values are the data to be submitted.

Step 2: Initialize cURL Handle

Use the curl_init($url) function to create a cURL handle for the target URL.

Step 3: Set CURLOPT_POST to True

Use curl_setopt($handle, CURLOPT_POST, true) to activate the HTTP POST method.

Step 4: Set CURLOPT_POSTFIELDS with URL Encoded Data

Encode the POST data array using http_build_query($data) and set it with curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data)). This ensures the data is encoded in the expected format.

Step 5: Execute and Close cURL Handle

Execute the request with curl_exec($handle) and close the handle with curl_close($handle).

Example Code:

<?php

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

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

?>
Copy after login

Important Notes:

  • Ensure that the target page is ready to receive POST data and expects the specific fields.
  • If submitting a file, you can use $data['file'] = '@/home/user/world.jpg' to prefix the file path with an @.
  • The data encoding format is determined by whether you pass an array or a URL encoded string to CURLOPT_POSTFIELDS.

The above is the detailed content of How to Pass POST Values 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template