How to use cURL in php?
CURL is the library account is used to help to make the transfer data through many other protocol (as HTTP, FPT …).
1. How to use CURL in PHP:
A CURL application typically has three basic steps:
Step 1: Initialize CURL: $ch = curl_init()
.
Step 2: Configure parameters for CURL:
curl_setopt($ch, CURLOPT_URL, "https://soltuts.com");
Curl_setopt(1,2,3) has 3 input parameters: 1 is a CURL object 2 is the configuration name 3 is the value Some common configuration names with CURL: CURLOPT_URL: path to the URL to be processed CURLOPT_RETURNTRANSFER: if true, the result will be returned to the curl_exec function, so we have to echo that result to print to the browser, if false, it will print the result to the browser. CURLOPT_USERAGENT: Used to simulate which browser is sending (user agent) CURLOPT_TIMEOUT: Set the lifetime of a CURL request CURLOPT_FILE: Save results to file CURLOPT_POSTFIELDS: its value is an array of keys => value, corresponding to its name and value in the input tags when submitting the FORM
Step 3: Execute CURL: curl_exec($ch);
Step 4: Break CURL, release data: curl_close($ch);
2. Example:
Post Data Using cURL:
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3' ); $fields_string = http_build_query($fields); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string); $data = curl_exec($curl); curl_close($curl);
Post JSON Data Using cURL:
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3' ); $json_string = json_encode($fields); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true ); $data = curl_exec($curl); curl_close($curl);
Upload Files Using cURL:
<?php $url = '{POST_REST_ENDPOINT}'; $curl = curl_init(); if (function_exists('curl_file_create')) { $fileAttachment = curl_file_create('/absolute/path/to/file/'); } else { $fileAttachment = '@' . realpath('/absolute/path/to/file/'); } $fields = array( 'field_name_1' => 'Value 1', 'field_name_2' => 'Value 2', 'field_name_3' => 'Value 3', 'uploaded_file' => $fileAttachment ); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $fields); curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); $data = curl_exec($curl); curl_close($curl);