Convert curl to PHP cURL

Convert curl commands to PHP cURL code. Learn curl_init, curl_setopt, and curl_exec patterns for GET, POST, authentication, and file upload operations.

PHP

Detailed Explanation

Converting curl to PHP cURL

PHP has built-in cURL support through the ext-curl extension, providing a direct mapping from command-line curl to PHP code. The PHP cURL API mirrors the underlying libcurl library.

GET Request

curl:

curl https://api.example.com/users

PHP:

$ch = curl_init("https://api.example.com/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

POST with JSON

curl:

curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'

PHP:

$ch = curl_init("https://api.example.com/users");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
    CURLOPT_POSTFIELDS => json_encode(["name" => "Alice"]),
]);
$response = curl_exec($ch);
curl_close($ch);

Authentication

curl:

curl -u user:pass https://api.example.com/data

PHP:

curl_setopt($ch, CURLOPT_USERPWD, "user:pass");

Error Handling

Always check for cURL errors in production code:

$response = curl_exec($ch);
if (curl_errno($ch)) {
    throw new Exception("cURL error: " . curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

Common Option Mapping

curl flag PHP constant
-L CURLOPT_FOLLOWLOCATION
-k CURLOPT_SSL_VERIFYPEER => false
--timeout CURLOPT_TIMEOUT
-x proxy CURLOPT_PROXY
-o file CURLOPT_FILE
-H CURLOPT_HTTPHEADER

Modern PHP Alternative

For newer projects, consider using Guzzle HTTP client, which provides a higher-level API similar to Python requests. However, the built-in cURL extension remains the most universally available option across PHP hosting environments.

Use Case

A PHP developer working on a WordPress plugin or Laravel application needs to make HTTP requests to external APIs and has curl examples from the API documentation.

Try It — Curl to Code Converter

Open full tool