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
Related
How do I convert the curl command below to PHP used with Laravel?
curl -X POST -F "images_file=#fruitbowl.jpg" "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=xxxxa12345&version=2016-05-20"
There is a function to upload file with curl php:
function uploadFileWithCURL($fullFilePath, $targetURL)
{
if (function_exists('curl_file_create')) {
$curlFile = curl_file_create($fullFilePath);
} else {
$curlFile = '#' . realpath($fullFilePath);
}
$post = array('file_contents' => $curlFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
Usage:
$result = uploadFileWithCURL('path/to/your/fruitbowl.jpg','https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=xxxxa12345&version=2016-05-20');
have a look at this package, this is a super easy curl wrapper for laravel
https://github.com/ixudra/curl
so it would look like
use Ixudra\Curl\Facades\Curl;
$response = Curl::to('https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=xxxxa12345&version=2016-05-20')
->withContentType('multipart/form-data')
->withData(['images_file' => file_get_contents("yourfile")])
->containsFile()
->post();
Use the Http facade and call the attach method, this method accepts the name of the file and its contents
use Illuminate\Support\Facades\Http;
$response = Http::attach(
'images_file', '/home/user/fruitbowl.jpg', 'fruitbowl.jpg'
)->post('https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classify?api_key=xxxxa12345&version=2016-05-20'
)->json();
https://laravel.com/docs/8.x/http-client#multi-part-requests
I want send post request from php to python and get answer
I write this script which the send post
$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);
I'm use custom python server
from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
And python script which the takes post request
print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("<p>TEXT_2: {}</p>".format(text2))
And then I get
write() argument must be str, not bytes\r\n'
How can it be solved?
P.S Sorry for my bad english
Check curl extension for php http://php.net/manual/en/book.curl.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://localhost:8080/cgi-bin/file.py");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// 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);
You can also use a library like guzzle that may have some other bells and whistles you may want to use.
Example usage can be found on this other answer here:
https://stackoverflow.com/a/29601842/6626810
I am building my first ever project from scratch on a lamp stack. I decided to try out the slim api framework. Below you can see i start building a helper function for my api. However I am getting this
error: undefined constant CURLOPT_GET - assumed 'CURLOPT_GET'
and then this
error: curl_setopt() expects parameter 2 to be long, string given
// Main Gospel Blocks API Call Function
Function gbCall($gbRoute) {
// JSON Headers
$gblCallHeaders[] = "Content-Type: application/json;charset=utf-8";
// Call the API
$gblCall = curl_init();
curl_setopt($gblCall, CURLOPT_URL, $GLOBALS['gbApiUrl'] . $gbRoute);
curl_setopt($gblCall, CURLOPT_GET, TRUE);
curl_setopt($gblCall, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($gblCall, CURLOPT_HTTPHEADER, $gblCallHeaders);
// Get the response
$response = curl_exec($gblCall);
// Close cURL connection
curl_close($gblCall);
// Decode the response (Transform it to an Array)
$response = json_decode($response, true);
// Return response
return $response;
}
The api I am hitting is just json encoded objects, not quite sure why this isn't returning the json...
Try using CURLOPT_HTTPGET though I am not sure if it serves your purpose.
More detail can be found here
It happens when phpxxx-curl was not installed in your machine
There is nothing like CURLOPT_GET in the options for cURL that's why that error occured. Take a look at CURL options
For the GET Request in the Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "URL");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "Key: Value";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');
I want to POST using HTTP_Request2 Pear Class. I was succefull when I used cURL to do the same, but I dont get response data when I use HTTP_Request. It says content length as 0. I read the PEAR documentation for HTTP_Request2 and followed it to write the code. It will be of great help if someone points out my errors. cURL method works but HTTP_Request2 method dosent. What I think is that the HTTP_Request2 method is unable to post the data, but I am not sure about the header too. My code is
function header()
{
$this->setGuid(guid());
$this->header = array($this->service,
time(), $this->getGuid());
return $this->header;
}
function header1()
{
$this->setGuid(guid());
$this->header = array('X-OpenSRF-service: '.$this->service,
'X-OpenSRF-xid: '.time(), 'X-OpenSRF-thread: '.$this->getGuid());
return $this->header;
}
function toArray()
{
$url4 = urldata($this->method, $this->param);
return $url4; //returns an encoded url
}
function send1()
{
require_once 'HTTP/Request2.php';
//------cURL Method-------------------------
$endpoint = $this->endpoint;
$data = $this->toArray();
$header = $this->header1();
$url_post = 'http://'.$endpoint.'/osrf-http-translator';
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, $url_post);
curl_setopt($this->curl, CURLOPT_HEADER, 1);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
$this->server_result = curl_exec($this->curl);
if (curl_error($this->curl) != 0 ) {
$error = 'Curl error: ' . curl_error($this->curl);
return $error;
}
var_dump ($this->server_result);
echo "<HR />";
//-----HTTP_REQUEST2 Method---------------
$request = new HTTP_Request2();
$request->setUrl($url_post);
$request->setHeader(array('X-OpenSRF-service' => $header[0], 'X-OpenSRF-xid' => $header[1], 'X-OpenSRF-thread' => $header[2]));
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->addPostParameter($data);
var_dump ($request); echo "<HR />";
$response = $request->send(); var_dump($response);
}
The result of the HTTP_Request2::send() method is a little different to curl_exec. It is not as string, but another type, namely HTTP_Request2_Response.
To retrieve the response body as a string (a HTTP response contains the headers and a body), use the HTTP_Request2_Response::getBody method:
...
$response = $request->send();
$responseBody = $response->getBody();
This should do what you're looking for, $responseBody then is a string. In more general terms: HTTP_Request2 has an object-oriented interface. This allows to use different adapters (e.g. Curl as well as sockets or you can even write your own one, e.g. for testing) as well as retrieving the response body in a streaming fashion (e.g. with large responses you do not put all into a single string at once).