Reputation: 11
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.
Upvotes: 1
Views: 4398
Reputation: 14946
Try using HTTP_Request2; it's not in standard PHP, but you can distribute it with your application so you don't have to worry about whether it's installed or not.
The following is a snippet from a class I use to POST a document to a conversion server; you can post whatever you like and get the results in a similar way.
$request = new HTTP_Request2('http://whereveryouwant:80/foo/');
$request->setMethod(HTTP_Request2::METHOD_POST)
->setConfig('timeout', CONVERT_SERVER_TIMEOUT)
->setHeader('Content-Type', 'multipart/form-data')
->addPostParameter('outputFormat', $outputType);
$request->addUpload('inputDocument', $inputFile);
$result = $request->send();
if ($result->getStatus() == 200) {
return $result->getBody();
} else {
return false;
}
Upvotes: 2
Reputation: 51411
There are plenty of pure-PHP HTTP handlers out there that might work better for you.
Try PEAR's HTTP_Client or Zend_Http_Client, both of which you can simply bundle with your application.
If you're dead-set on writing your own, try working with streams. There's a comprehensive set of HTTP stream options to choose from.
Upvotes: 2
Reputation: 23255
It might be simpler to write this by using the http extension : http://fr.php.net/manual/en/function.http-post-data.php
Upvotes: 0