Tags
Asked 2 years ago
9 Jun 2021
Views 175
ajamil

ajamil posted

how to call a simple post request and retrival of page example in php with curl?

how to call a simple post request and retrival of page example in php with curl?
steave ray

steave ray
answered Apr 26 '23 00:00

Here's an example of how to call a simple POST request and retrieve the response using cURL in PHP:



$url = "https://www.example.com/login.php";
$data = array(
    'username' => 'myusername',
    'password' => 'mypassword'
);

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url); // URL to call
curl_setopt($ch, CURLOPT_POST, true); // POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return response as string

// Execute cURL session
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Process the response
echo "Response: " . $response;

In this example, we specify the URL to call and the POST data to send in an array. We set the CURLOPT_POST option to true to indicate that this is a POST request and set the CURLOPT_POSTFIELDS option to the POST data. We also set the CURLOPT_RETURNTRANSFER option to true to return the response as a string.

After executing the cURL session, we process the response by simply echoing it.

Note that you may need to adjust the CURLOPT_POSTFIELDS option depending on the format of the POST data you need to send. For example, if the data needs to be sent as JSON, you would need to use json_encode () to convert the data to a JSON string and set the Content-Type header accordingly using the CURLOPT_HTTPHEADER option.
Post Answer