cURL Command Builder — PHP source
Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
// curl-builder — structured input → copy-paste curl command + reverse parser.
// PHP port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
// Composes a copy-paste curl command from structured input; also parses an
// existing command back into the structure (round-trip). Values are single-
// quoted with embedded quotes escaped (' → '\'') — safe for POSIX shells.
// The flag order is fixed and deterministic: method (-X) → headers (-H,
// insertion order) → auth (-u) → data (-d) → boolean flags (-I -k -L
// --compressed) → the URL last. The request is an assoc array (snake_case
// keys: url, method, headers [{key,value}], data, auth {user,password},
// head_only, insecure, follow_redirects, compressed; missing = unset).
// Never throws — errors travel in the result array ('error' => null).
const CURL_BUILDER_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
/** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
function curl_builder_shell_quote(string $value): string
{
return "'" . str_replace("'", "'\\''", $value) . "'";
}
/** Build the curl command. URL required; method/header names validated. */
function curl_builder_build(array $req): array
{
$url = trim($req['url'] ?? '');
if ($url === '') {
return ['command' => '', 'error' => 'A URL is required'];
}
if (!preg_match('/^(https?:\/\/|\/|\$)/', $url)) {
return ['command' => '', 'error' => 'URL must start with http://, https://, / or $ (a variable)'];
}
$method = strtoupper($req['method'] ?? 'GET');
if (!in_array($method, CURL_BUILDER_METHODS, true)) {
return ['command' => '', 'error' => 'unsupported method ' . ($req['method'] ?? '')
. ' (use ' . implode(', ', CURL_BUILDER_METHODS) . ')'];
}
foreach ($req['headers'] ?? [] as $h) {
if (!preg_match('/^[A-Za-z0-9-]+$/', $h['key'] ?? '')) {
return ['command' => '', 'error' => 'invalid header name "' . ($h['key'] ?? '')
. '" (letters, digits and hyphens only)'];
}
}
$parts = ['curl'];
if ($method !== 'GET') {
$parts[] = "-X $method";
}
foreach ($req['headers'] ?? [] as $h) {
$parts[] = '-H ' . curl_builder_shell_quote(($h['key'] ?? '') . ': ' . ($h['value'] ?? ''));
}
if (isset($req['auth'])) {
$parts[] = '-u ' . curl_builder_shell_quote(($req['auth']['user'] ?? '') . ':' . ($req['auth']['password'] ?? ''));
}
if (isset($req['data']) && $req['data'] !== '') {
$parts[] = '-d ' . curl_builder_shell_quote($req['data']);
}
if (!empty($req['head_only'])) $parts[] = '-I';
if (!empty($req['insecure'])) $parts[] = '-k';
if (!empty($req['follow_redirects'])) $parts[] = '-L';
if (!empty($req['compressed'])) $parts[] = '--compressed';
$parts[] = curl_builder_shell_quote($url);
return ['command' => implode(' ', $parts), 'error' => null];
}
/** Shell word-split respecting single and double quotes. */
function curl_builder_split_words(string $line): array
{
$words = [];
$cur = '';
$quote = null;
$has = false;
foreach (str_split($line) as $ch) {
if ($quote !== null) {
if ($ch === $quote) {
$quote = null;
} else {
$cur .= $ch;
}
} elseif ($ch === "'" || $ch === '"') {
$quote = $ch;
$has = true;
} elseif ($ch === ' ' || $ch === "\t") {
if ($cur !== '' || $has) {
$words[] = $cur;
}
$cur = '';
$has = false;
} else {
$cur .= $ch;
$has = true;
}
}
if ($has) {
$words[] = $cur; // any accumulated characters imply has
}
return $words;
}
/** Parse a curl command line back into a request (best effort, ordered). */
function curl_builder_parse(string $line): array
{
$trimmed = trim($line);
if ($trimmed === '') {
return ['parsed' => null, 'error' => 'A command is required'];
}
$words = curl_builder_split_words(str_replace("\\\n", ' ', $trimmed));
if (($words[0] ?? '') !== 'curl') {
return ['parsed' => null, 'error' => 'command must start with curl'];
}
$req = ['url' => '', 'headers' => []];
$unknown = [];
$n = count($words);
for ($i = 1; $i < $n; $i++) {
$w = $words[$i];
if ($w === '-X' || $w === '--request') {
if ($i + 1 < $n) $req['method'] = $words[++$i];
} elseif ($w === '-H' || $w === '--header') {
if ($i + 1 < $n) {
$raw = $words[++$i];
$at = strpos($raw, ':');
if ($at !== false && $at > 0) {
$req['headers'][] = ['key' => trim(substr($raw, 0, $at)), 'value' => trim(substr($raw, $at + 1))];
}
}
} elseif ($w === '-u' || $w === '--user') {
if ($i + 1 < $n) {
$raw = $words[++$i];
$at = strpos($raw, ':');
if ($at === false) {
$req['auth'] = ['user' => $raw, 'password' => ''];
} else {
$req['auth'] = ['user' => substr($raw, 0, $at), 'password' => substr($raw, $at + 1)];
}
}
} elseif ($w === '-d' || $w === '--data') {
if ($i + 1 < $n) $req['data'] = $words[++$i];
} elseif ($w === '-I' || $w === '--head') { $req['head_only'] = true; }
elseif ($w === '-k' || $w === '--insecure') { $req['insecure'] = true; }
elseif ($w === '-L' || $w === '--location') { $req['follow_redirects'] = true; }
elseif ($w === '--compressed') { $req['compressed'] = true; }
elseif (str_starts_with($w, '-')) { $unknown[] = $w; }
else { $req['url'] = $w; }
}
if (($req['url'] ?? '') === '') {
return ['parsed' => null, 'error' => 'no URL found in command'];
}
return ['parsed' => ['request' => $req, 'unknown_flags' => $unknown], 'error' => null];
}
// Example:
// curl_builder_shell_quote("it's") → "'it'\\''s'"
// curl_builder_build(['url' => 'https://api.example.com', 'method' => 'post',
// 'headers' => [['key' => 'X-Tag', 'value' => "it's"]], 'data' => 'k=v'])['command']
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"
// curl_builder_parse("curl -sL --compressed 'https://x.dev'")
// → ['parsed' => ['request' => ['url' => 'https://x.dev', 'headers' => [], 'compressed' => true], 'unknown_flags' => ['-sL']], 'error' => null]
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →