How to send a POST request in PHP with Curl

Published by bruxo on

To send POST request with PHP, it’s very simple.

You just need to use this function, and you can configure the port, post parameters, etc.

function curl_post($url, $port, array $post = null, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_PORT => $port,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post),
    );
    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if (!$result = curl_exec($ch)) {
        trigger_error(curl_error($ch));
        return "Error";
    }
    curl_close($ch);
    return $result;
}

 

And you can use it like:

 

$response = curl_post("https://api.example.com/", 433, array('test' => 'hello'));
echo $response;
Categories: PHPWeb

Leave a Reply

Your email address will not be published. Required fields are marked *