I’ve been working on a project that involves converting a command-line curl
command into a PHP curl
request. I’ll walk you through my process, explain my original code, and then share an enhanced version that includes practical improvements such as input validation, proper header settings, error handling, and a more flexible design.
Explanation of the Original Code
Setting the API Endpoint
$url = 'http://localhost:11434/api/chat -d';
At first, I tried to define the URL for the POST request. However, I made the mistake of including the -d
command-line flag in the URL. The -d
flag is used in the command line to specify data, but it should not be part of the URL in PHP.
Getting the Question Parameter
$question = $_GET["q"];
Next, I retrieved the question from the URL’s query parameter named q
. This value represents the user’s message that I want to send to the API.
Defining the Request Data
$model = 'deepseek-r1:1.5b';
$data = array(
"model" => $model,
"messages" => array(
array(
"role" => "user",
"content" => $question,
)
),
);
I created an associative array that contains the model and an array of messages. In this case, there is only one message with the role “user” and the content provided by the q
parameter.
Encoding the Data as JSON
$payload = json_encode($data);
I used PHP’s json_encode
function to convert the data array into a JSON string. This JSON payload is what the API expects to receive.
Initializing and Configuring cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Here’s what’s happening in this section:
curl_init($url)
: Initializes a new cURL session with the specified URL.CURLOPT_CUSTOMREQUEST
: Sets the request method to POST.CURLOPT_POSTFIELDS
: Attaches the JSON payload to the request body.CURLOPT_RETURNTRANSFER
: Tells cURL to return the response as a string rather than directly outputting it.
Executing the cURL Request and Handling the Response
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
echo $response;
Finally, I executed the POST request, closed the cURL session, decoded the JSON response into a PHP array, and attempted to output the response. However, directly echoing an array isn’t effective, so I knew I needed a better way to display the output.
Enhanced PHP Code with Practical Functionality
After some troubleshooting and refinement, I came up with an improved version of my PHP script. The new version fixes the URL issue, adds input validation, sets the appropriate HTTP headers, and includes robust error handling.
<?php
// Define the API endpoint URL correctly (without the '-d')
$url = 'http://localhost:11434/api/chat';
// Validate that the 'q' parameter is provided
if (!isset($_GET["q"]) || empty(trim($_GET["q"]))) {
http_response_code(400);
echo json_encode(["error" => "Missing 'q' parameter in query string."]);
exit;
}
$question = trim($_GET["q"]);
$model = 'deepseek-r1:1.5b';
// Create the data array for the request
$data = array(
"model" => $model,
"messages" => array(
array(
"role" => "user",
"content" => $question,
)
),
);
// Convert the data array to a JSON string
$payload = json_encode($data);
// Initialize cURL
$ch = curl_init($url);
// Set cURL options for the POST request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set HTTP headers for JSON content
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
));
// Execute the cURL request
$result = curl_exec($ch);
// Check for cURL errors
if ($result === false) {
$error = curl_error($ch);
curl_close($ch);
http_response_code(500);
echo json_encode(["error" => "cURL error: $error"]);
exit;
}
// Close the cURL session
curl_close($ch);
// Decode the JSON response
$response = json_decode($result, true);
// Output the response in a readable JSON format
header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
?>
Key Enhancements in the Revised Code
- Correct URL Usage:
I removed the-d
flag from the URL, ensuring that the API endpoint is correctly addressed. - Input Validation:
The script now checks if the required query parameterq
exists and isn’t empty. If it is missing, a 400 HTTP status code is returned along with an error message. This prevents unnecessary API calls with invalid input. - HTTP Headers for JSON:
Setting theContent-Type
header toapplication/json
informs the API that the request body is JSON. I also included theContent-Length
header, which specifies the size of the payload. - Error Handling:
I added checks to see if the cURL execution returnsfalse
and then capture and return the error message. This includes sending proper HTTP response codes to indicate an error has occurred. - Proper Response Output:
Instead of trying to echo a PHP array directly, the response is encoded as JSON (with pretty print) for easy reading by the client.
Final Thoughts
I am really pleased with the improvements this enhanced PHP code brings to converting a command-line curl
command into a PHP-based one. The new version not only resolves the initial issues but also adds robust input validation, error handling, and proper response formatting. This ensures that the script is more reliable and easier to integrate into larger applications.
Converting command-line tools into web-friendly versions is a crucial part of modern development, and I hope this example inspires you to apply similar enhancements in your projects. Remember, clean code, proper error handling, and clear output can save you a lot of debugging time down the road.