Skip to content

Instantly share code, notes, and snippets.

@cba85
Created October 19, 2022 15:49
Show Gist options
  • Save cba85/8631d5caa9fb10bbc372bf4a2101ac19 to your computer and use it in GitHub Desktop.
Save cba85/8631d5caa9fb10bbc372bf4a2101ac19 to your computer and use it in GitHub Desktop.
PHP Curl (For demonstration purpose only)
<?php
// For demonstration purpose only
// API using CURL
// Get
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://hacker-news.firebaseio.com/v0/topstories.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$results = curl_exec($ch);
$infos = curl_getinfo($ch);
print_r($infos);
if ($infos['http_code'] !== 200) {
echo 'Oops! Something went wrong!';
die();
}
$topStoryIds = array_slice(json_decode($results), 0, 5);
print_r($topStoryIds);
die();
// Post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://0.0.0.0:8080/server.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'text' => 'Webstart is nice!'
]);
$result = curl_exec($ch);
$response = json_decode($result);
if (curl_getinfo($ch)['http_code'] !== 200) {
echo $response->data->error;
die();
}
echo $response->data->text;
print_r($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment