Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created October 24, 2017 01:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xeoncross/fbc7fa602e9cbd692b4257fc09b908fc to your computer and use it in GitHub Desktop.
Save xeoncross/fbc7fa602e9cbd692b4257fc09b908fc to your computer and use it in GitHub Desktop.
POST requests using curl, sockets, and php-curl
<?php
// command line
// curl --data "text=foobar" http://localhost:3001/api/decrypt
// File sockets
function http_request($url, $data, $a = null, $b = null) {
$opts = array('http' =>
array(
'method' => 'POST',
// 'header' => 'Content-type: application/x-www-form-urlencoded',
// 'content' => http_build_query($data),
'header' => 'Content-type: application/json',
'content' => json_encode($data)
)
);
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
// curl
function curl_request($url, $data, $json = true, $log = false)
{
$headers = ['Connection: close'];
if($json) {
$headers[] = 'Content-Type: application/json; charset=utf-8';
$data = json_encode($data);
} else {
$headers[] = 'Content-Type: multipart/form-data';
$data = http_build_query($data);
}
$options = [
CURLOPT_RETURNTRANSFER => 1, // return web page's output
CURLOPT_HTTPHEADER => $headers, // all the auth stuff etc
CURLOPT_HEADER => false, // don't return headers
// CURLINFO_HEADER_OUT => true,
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_USERAGENT => "curl", // who am i?
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 20, // timeout on connect
CURLOPT_TIMEOUT => 20, // timeout on response
CURLOPT_MAXREDIRS => 3, // stop after 2 redirects
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
CURLOPT_POST => 1, // POST method
CURLOPT_POSTFIELDS => $data, // everything we are posting
];
if($log) {
// $verbose = fopen('./curl.log', 'w+');
$verbose = tmpfile();
$options[CURLOPT_VERBOSE] = true;
$options[CURLOPT_STDERR] = $verbose;
}
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$response = [
"body" => curl_exec($ch),
"info" => curl_getinfo($ch),
"error" => curl_error($ch)
];
if($log) {
rewind($verbose);
$response["log"] = stream_get_contents($verbose);
fclose($verbose);
}
curl_close($ch);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment