📜  CURL PHP POST - PHP (1)

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

CURL PHP POST

CURL is a versatile library for making HTTP requests in PHP. CURL supports various protocols including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, LDAP, DAP, Telnet and more. In this article, we will focus on using CURL PHP to make a POST request.

The CURL PHP POST Function

To make a CURL PHP POST request, we need to set the CURLOPT_POST option to true and provide the POST data as a string. Here is the code snippet to make a CURL PHP POST request:

$url = 'https://example.com/api';
$data = array('name' => 'John Doe', 'email' => 'john.doe@example.com');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

echo $response;

Let's go through each line of the code:

  1. $url - The URL we want to send the POST request to.
  2. $data - An associative array of the POST data we want to send.
  3. $ch - The CURL handle to initialize.
  4. curl_setopt() - Set various CURL options.
  5. CURLOPT_URL - Set the URL to send the request to.
  6. CURLOPT_POST - Set the request method to POST.
  7. CURLOPT_POSTFIELDS - Set the POST data as a string. We use http_build_query() to create a URL encoded string.
  8. CURLOPT_RETURNTRANSFER - Set to true to return the response as a string.
  9. curl_exec() - Execute the CURL request.
  10. curl_close() - Close the CURL handle.
  11. echo $response - Output the response.
Handling Errors

In case of any errors, CURL PHP returns false. We can use the curl_error() and curl_errno() functions to get more information about the error. Here is an updated code snippet that handles any errors:

$url = 'https://example.com/api';
$data = array('name' => 'John Doe', 'email' => 'john.doe@example.com');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if(curl_errno($ch)) {
    echo 'CURL Error: ' . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
Conclusion

In this article, we learned how to make a CURL PHP POST request, and how to handle any errors that may occur. CURL is a powerful library that can be used to make HTTP requests in PHP, and the POST request is one of the most common HTTP requests that we need to make.