PHP – Using fsockopen to post JSON data


<?php
require_once 'common/RESTClient.php';
$_hostname = $_POST['hostname'];
$jsonData = "{  \"hostname\" : \"$_hostname\"  }";
$client = new RESTClient;
$response = "";
$onStage = On_Stage_Server();
if($onStage)
{
	//echo "Stage";
	$response = $client->post("http://server-name/getHostname.php", $jsonData);
}
else
{
	//echo "Production";
	$response = curl_request_async($url, $jsonData);
}
echo $response."\n";
// ---------------------------------------------
// ---------------------------------------------
function curl_request_async($url, $jsonData)
{
	if (!On_Stage_server())
	{
		$out="";
		$url = "ssl://SERVER-IP/Name";
		//echo " JSON : $jsonData ";
		$fp = fsockopen ($url,443);//, $errno, $errstr, 15);
		$out ="POST /Path_To_API/getHostname.php HTTP/1.1\r\n";
		//$out.= "Host: ".$parts['host']."\r\n";
		$out.= "Host: [Server-IP]\r\n";
		$out.= "Content-Type: application/json\r\n";
		$out.= "Content-Length: ".strlen($jsonData)."\r\n";
		$out.= "Connection: Close\r\n\r\n";
		$out .= $jsonData;
		fwrite($fp, $out);
		header('Content-type: text/plain');
		$lineBreak = 0;
		while (!feof($fp))
		{
			if($lineBreak == 0)
			while(trim(fgets($fp, 2014)) != "")
			{
				$lineBreak = 1;
				continue;
			}
	
			$line = fgets($fp, 1024);
			$response .= "$line";
		}	

		fclose($fp);
		return $response;
	} 
	else 
	{
		// On Stage - Not being used
		/*
		echo "<h1>Data from server /Path_To_API/eval.php</h1>";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'http://Path_To_API/getHostnameProxy.php');
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		curl_setopt($ch, CURLOPT_REFERER, $referer);

		$response = curl_exec($ch);
		curl_close($ch);
		*/
	}
}
function On_Stage_Server()
{
	$hostname=$_SERVER['SERVER_NAME'];
	//echo $hostname."\n";
	if (preg_match("|^prodServer.net$|",$hostname) or preg_match("|^prodServer-Proxy.net$|",$hostname))
		return false;
	else
		return true;
}

?>

Advertisements
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s