Skip to content

Instantly share code, notes, and snippets.

@plonknimbuzz
Created May 10, 2022 09:39
Show Gist options
  • Save plonknimbuzz/d9fc131b14d0637f87428b1e5fade059 to your computer and use it in GitHub Desktop.
Save plonknimbuzz/d9fc131b14d0637f87428b1e5fade059 to your computer and use it in GitHub Desktop.
PHP Curl Forwarder
<?php
$data = json_decode(file_get_contents('php://input'));
$url = null;
if($data){
$request_type = 'JSON';
$url = isset($data->target_url)?$data->target_url:null;
}elseif(isset($_POST)){
$request_type = 'POST';
$data = isset($_POST)?$_POST:null;
if(isset($data['target_url'])){
$url = $data['target_url'];
unset($data['target_url']);
}
}else{
$request_type = 'GET';
$data = isset($_GET)?$_GET:null;
if(isset($data['target_url'])){
$url = $data['target_url'];
unset($data['target_url']);
}
}
if(!filter_var($url, FILTER_VALIDATE_URL)){
die('url target not valid');
}
$option = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $request_type=='GET'?'GET':'POST',
);
$headers = [];
if($request_type=='POST' && !empty($data)){
$option[CURLOPT_POSTFIELDS]=http_build_query($data);
}elseif($request_type=='JSON' ){
if(!empty($data)){
}
$headers[] ='Content-Type: application/json';
}
$allheaders = getRequestHeaders();
foreach ($allheaders as $header => $value) {
$headers[] = "$header:$value";
}
if($headers){
$option[CURLOPT_HTTPHEADER]=$headers;
}
$curl = curl_init();
curl_setopt_array($curl, $option);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
function getRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment