Link Search Menu Expand Document

HTTP Requests in PHP

Use the cURL functions in PHP to make HTTP requests and observe the response.

Here’s some helpful references from PHP’s documentation:

POST

// Initialize a new session handle.
$ch = curl_init();
curl_setopt_array(
	$ch,
	[
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_POST => true,
		CURLOPT_URL => 'https://functionschallenge.digitalocean.com/api/sammy',
		CURLOPT_HTTPHEADER => [
			'Accept: application/json',
			'Content-Type: application/json'
		],
		CURLOPT_POSTFIELDS => json_encode( $args ),
	]
);

// Send the request.
$response = curl_exec( $ch );

// Inspect the response.
error_log( print_r( $response, true ) );
error_log( print_r( curl_getinfo( $ch ), true ) );

// Close the session and free resources.
curl_close( $ch );