PHP post request to retrieve JSON
- by Brian
I'm trying to write some simple php code that will make a post request and then retrieve a JSON result from the server.
It seemed simple to me, but the below code simply doesn't open a connection.
$port = 2057;
$path = "/validate/";
$request = "value1=somevalue&value2=somevalue&value3=somevalue";
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $server\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($request) . "\r\n";
$http_request .= "\r\n";
$http_request .= $request;
$response = '';
if( false == ( $fs = @fsockopen($server, $port) ) ) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
while ( !feof($fs) )
{
$response .= fgets($fs, 1160);
}
fclose($fs);
In addition I've tried a more simple approach with:
$handle = fopen('http://localhost:2057/validate/?'.$request, "r");
or
$response = file_get_contents('http://localhost:2057/validate/' . $request);
but both of these approaches just time out.
I'm trying to connect to a development server I'm running in Visual Studio, so I'm not sure if that has anything to do with the timeout/connection issues.
Open to any suggestions here as long as they are built in PHP.