📜  php curl post - PHP (1)

📅  最后修改于: 2023-12-03 15:33:28.315000             🧑  作者: Mango

PHP CURL POST

CURL is a library that allows PHP to send HTTP requests and receive responses like a web browser. The library can handle various protocols and provide a consistent interface for working with them.

In PHP, CURL can be used to send HTTP POST requests to a server. In this article, we will explore how to use CURL to send POST requests in PHP.

Installation of CURL

CURL library is usually packaged with PHP, but in some cases, it may be missing. In this case, we can install CURL manually. To install CURL on Ubuntu or Debian, run the following command in your terminal:

sudo apt-get install php-curl
Sending POST Requests with CURL

To send a POST request with CURL, we need to set the POSTFIELDS option to the data we want to send. We can also set other options like the URL, user agent, and headers. Here is an example of sending a POST request to a server:

$url = 'https://example.com/api';
$data = ['name' => 'John', 'age' => 30];

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);

curl_close($curl);

echo $response;

In this example, we first set the URL we want to send the request to and the data we want to send. We then initialize a CURL handle and set the options.

We set the URL option to the URL we want to send the request to, the POST option to true to indicate that we want to send a POST request, and the POSTFIELDS option to the data we want to send.

We also set the RETURNTRANSFER option to true to indicate that we want CURL to return the response instead of outputting it directly.

Finally, we send the request using the curl_exec() function and close the CURL handle using the curl_close() function. We then output the response to the user.

Conclusion

Sending POST requests with CURL in PHP is easy and can be done with just a few lines of code. By setting the right options, we can send data to any server that can handle HTTP requests.