How to use a "curl -x post" command with query in php?

by raphael_tillman , in category: PHP General , 8 months ago

How to use a "curl -x post" command with query in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 8 months ago

@raphael_tillman 

To use a "curl -X POST" command with a query in PHP, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$url = 'http://example.com/api-endpoint';
$queryData = array(
    'param1' => 'value1',
    'param2' => 'value2'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($queryData));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if($response === false){
    echo 'Curl error: ' . curl_error($ch);
}else{
    echo $response;
}

curl_close($ch);


Replace http://example.com/api-endpoint with the actual endpoint URL you want to send the POST request to. Replace 'param1' => 'value1' and 'param2' => 'value2' with the actual query parameters and values you want to send in the POST request.


This code snippet sets up a cURL request with the specified URL, POST method, and query parameters. It then executes the request and retrieves the response. Finally, it either echoes the response or displays a curl error if there was a problem with the request.