Skip to content

Instantly share code, notes, and snippets.

@faizzed
Last active February 23, 2020 08:30
Show Gist options
  • Save faizzed/11096a12f92a553d43a0286c9ec878db to your computer and use it in GitHub Desktop.
Save faizzed/11096a12f92a553d43a0286c9ec878db to your computer and use it in GitHub Desktop.
php curl request module
<?php
/**
* A nice little request module using php curl,
* handy for looking up things quickly. Not intended for any major purpose
* or tweak it yourself
*
* @param $url string
* @param $method string
* @param $data array
* @param $headers array
* @return mixed
* */
function request(
$url = 'https://www.google.com',
$method = 'GET',
$data = [],
$headers = []
)
{
$ch = curl_init();
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// get request
print_r(
request('http://dummy.restapiexample.com/api/v1/employees')
);
// post request
print_r(
request('http://dummy.restapiexample.com/api/v1/create', $method = 'POST', $data = [
'name' => 'Foo'
], $headers = [
'Content-type: application/json'
])
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment