I am using the HttpRequest class in my php script, but when I uploaded this script to my hosting provider's server, I get a fatal error when executing it:
Fatal error: Class 'HttpRequest' not found in ... on line 87
I believe the reason is because my hosting provider's php.ini configuration doesnt include the extension that supports HttpRequest. When i contacted them they said that we cannot install the following extentions on shared hosting.
So i want the alternative for httpRequest which i make like this:
$url= http://ip:8080/folder/SuspendSubscriber?subscriberId=5
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
return $response;
Or How can i use this request in curl as it is not working for empty datastring?
You can use CURL in php like this:
$ch = curl_init( $url );
$data_string = " ";
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
and empty data string doesn't make sense in post request, but i've checked it with empty data string and it works quiet well.
you can use a framework like zend do this. framework usually have multiple adapters (curl,socket,proxy).
here is a sample with ZF2:
$request = new \Zend\Http\Request();
$request->setUri('[url]');
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getPost()->set('key', $value);
$client = new \Zend\Http\Client();
$client->setEncType('application/x-www-form-urlencoded');
$response = false;
try {
/* @var $response \Zend\Http\Response */
$response = $client->dispatch($request);
} catch (Exception $e) {
//handle error
}
if ($response && $response->isSuccess()) {
$result = $response->getBody();
} else {
$error = $response->getBody();
}
you don't have to use the entire framework just include (or autoload) the classes that you need.
Use the cURL
in php
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.com/feed.rss");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"postvar1=value1&postvar2=value2");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
for more see this PHP Difference between Curl and HttpRequest
a slight variaton on the curl methods proposed, i decode the json that is returned, like in this snippet