PHP CURL Sample

Authored by
function send_post_request($url, $data = array()) {
    // Initialize cURL session
    $curl = curl_init();
    
    // Set the URL to send the POST request to
    curl_setopt($curl, CURLOPT_URL, $url);
    
    // Set the request method to POST
    curl_setopt($curl, CURLOPT_POST, true);
    
    // Set the POST data
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    }
    
    // Set cURL options to include response headers in the output
    curl_setopt($curl, CURLOPT_HEADER, false);
    
    // Set cURL option to return the response as a string
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
    // Execute cURL session and store the response
    $response = curl_exec($curl);
    
    // Check for errors
    if($response === false) {
        // If there was an error, return the error message
        $error_message = curl_error($curl);
        curl_close($curl);
        return "cURL Error: " . $error_message;
    }
    
    // Close cURL session
    curl_close($curl);
    
    // Return the response
    return $response;
}

// Example usage:
$url = "https://example.com/api";
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$response = send_post_request($url, $data);
echo $response;

 

Other Code Snippets

Change Permissions or Ownership of Files or Directories Recursively

Code Snippet | Linux

Sometimes when you are moving files from one host to another, you have to change the files owner or permissions so the web server can utilize it properly.

Read More
Find Files by Size

Code Snippet | Linux

Here is a Linux command line that searches for files that are over a certain size so that you can find where you might be able to free up some space. Useful to find error_logs that have run amok.

Read More
Import MySQL from Command Line

Code Snippet | Linux | MySQL

Here is a method to import a SQL file into a database via the Linux command line.

Read More
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram