Created
October 24, 2017 01:49
-
-
Save xeoncross/fbc7fa602e9cbd692b4257fc09b908fc to your computer and use it in GitHub Desktop.
POST requests using curl, sockets, and php-curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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