# PHP cURL (Client URL Library)

**cURL** allows you to connect and communicate to many different types of servers with many different types of protocols (HTTP, FTP, etc.). It is widely used to send API requests.

---

## 1. Basic Workflow
Using cURL in PHP generally follows these four steps:
1.  **Initialize** a cURL session.
2.  **Set options** (URL, method, headers, etc.).
3.  **Execute** the session.
4.  **Close** the session.

```php
$ch = curl_init(); // 1. Initialize
curl_setopt($ch, CURLOPT_URL, "http://example.com"); // 2. Set Options
curl_exec($ch); // 3. Execute
curl_close($ch); // 4. Close
```

## 2. Making a GET Request
By default, cURL uses GET. To receive the response as a string instead of outputting it directly, use `CURLOPT_RETURNTRANSFER`.

```php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
```

## 3. Making a POST Request
To send data (like form submissions or JSON APIs), use `CURLOPT_POST` and `CURLOPT_POSTFIELDS`.

```php
$url = "https://api.example.com/users";
$data = ['name' => 'John', 'role' => 'admin'];

$ch = curl_init($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);
```

## 4. Common Options
*   `CURLOPT_URL`: The URL to fetch.
*   `CURLOPT_RETURNTRANSFER`: Return the transfer as a string instead of outputting it.
*   `CURLOPT_TIMEOUT`: The maximum number of seconds to allow cURL functions to execute.
*   `CURLOPT_HTTPHEADER`: An array of HTTP header fields to set (e.g., `['Content-Type: application/json']`).

## 5. Error Handling
Always check for errors when making requests.

```php
if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}
```

[[programming/php/php]] [[programming/php/php-json]]